Не может получить из пружинного бэкэнда из -за CORSJAVA

Программисты JAVA общаются здесь
Anonymous
Не может получить из пружинного бэкэнда из -за CORS

Сообщение Anonymous »

У меня есть бэкэнд с использованием пружины и фронта, используя React.
У меня уже есть много контроллеров, и все методы работают с текущими Cors: < /p>

Код: Выделить всё

@Configuration
public class Cors {

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:5173");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}

}
< /code>
Стоит отметить, что я не использую Spring Security.
Это мой pom: < /p>



org.springframework.boot
spring-boot-starter-web



org.springframework.security
spring-security-crypto
6.1.4



org.springframework.boot
spring-boot-starter-data-jpa



org.postgresql
postgresql
42.7.2



org.projectlombok
lombok
1.18.36
provided



< /code>
Теперь у меня есть этот контроллер и единственный метод, который не работает: < /p>
DTO и метод контроллера (/edit
не работает):

Код: Выделить всё

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Jacksonized
public class EditCommentRequest {
private long commentId;
private boolean isPublished;
}

@RestController
@RequestMapping("/api/comment")
public class CommentController {

final CommentService commentService;

public CommentController(CommentService commentService) {
this.commentService = commentService;
}

@GetMapping("/get-all")
public ResponseEntity getAllComments() {
List comments = commentService.getAll();
return ResponseEntity.status(HttpStatus.OK).body(comments);
}

@PostMapping("/edit")
public ResponseEntity editComment(
@RequestBody EditCommentRequest request,
HttpSession session) {

commentService.updateCommentStatus(request, (Long) session.getAttribute(USER_ID));
return ResponseEntity.status(HttpStatus.OK).build();
}
}
Дело в том, что это метод @postmapping ("/edit") , который не работает при извлечении из фронта (все остальные работают хорошо, проблема именно в этом)
Это извлечено из React:

Код: Выделить всё

const handleSendEditCommentData = async (event) => {
event.preventDefault();

const requestData = {
commentId: data.id,
isPublished: isCommentShowCheckbox,
};

console.log(requestData);

try {
const response = await fetch(API_ENDPOINTS.COMMENT_EDIT, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestData),
});

if (response.ok) {
onClose();
getAllData();
toast.success("Comment edited successfully.");
} else {
const errorData = await response.json();
switch (response.status) {
case 401:
toast.error(errorData.message || "401");
break;
case 404:
toast.error(errorData.message || "404");
break;
case 409:
toast.error(errorData.message || `409`);
break;
case 500:
toast.error(errorData.message || "500");
break;
default:
toast.error(`Else error`);
break;
}
}

} catch (error) {
console.error("Fetch Error:", error);
toast.error("catch error: "  + error.message);
}
< /code>
Этот метод вызывается, нажав на кнопку (onClick={handleSendEditCommentData}
)
Все данные, которые помещаются в тело: CommentId (), ispublished (), используются нормально, CommentId - это просто идентификатор через реквизиты, а Ispublised - простой Bool usEState , который устанавливается пользователем.
Этот метод извлечения всегда сбоя в Catch: Catch Orer: не удалось получить
console log:
Access to fetch at 'http://localhost:21001/api/comment/edit' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

POST http://localhost:21001/api/comment/edit net::ERR_FAILED

Fetch Error: TypeError: Failed to fetch
at handleSendEditCommentData (EditCommentModal.jsx:29:36)
at HTMLUnknownElement.callCallback2 (chunk-3F5266CN.js?v=a9e8ce0e:3680:22)
at Object.invokeGuardedCallbackDev (chunk-3F5266CN.js?v=a9e8ce0e:3705:24)
at invokeGuardedCallback (chunk-3F5266CN.js?v=a9e8ce0e:3739:39)
at invokeGuardedCallbackAndCatchFirstError (chunk-3F5266CN.js?v=a9e8ce0e:3742:33)
at executeDispatch (chunk-3F5266CN.js?v=a9e8ce0e:7046:11)
at processDispatchQueueItemsInOrder (chunk-3F5266CN.js?v=a9e8ce0e:7066:15)
at processDispatchQueue (chunk-3F5266CN.js?v=a9e8ce0e:7075:13)
at dispatchEventsForPlugins (chunk-3F5266CN.js?v=a9e8ce0e:7083:11)
at chunk-3F5266CN.js?v=a9e8ce0e:7206:20
< /code>
Здесь отправлены два запроса, и оба они не получают ответа, в Devtools они отмечены красным, < /p>
Сначала - Статус: Ошибка Cors, тип: Fetch < /p>
Request URL:
http://localhost:21001/api/comment/edit
Referrer Policy:
strict-origin-when-cross-origin

RESPONE HEADERS:
none

REQUEST HEADDERS:
content-type:
application/json
referer:
http://localhost:5173/
sec-ch-ua:
"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile:
?0
sec-ch-ua-platform:
"Windows"
user-agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36

PAYLOAD:
{commentId: 5, isPublished: true}
commentId: 5
isPublished: true
< /code>
Второе - Статус: 401, Тип: Предультура < /p>
Request URL:
http://localhost:21001/api/comment/edit
Request Method:
OPTIONS
Status Code:
401 Unauthorized
Remote Address:
[::1]:21001
Referrer Policy:
strict-origin-when-cross-origin

RESPONE HEADERS:
connection:
keep-alive
content-length:
0
date:
Sat, 08 Mar 2025 08:40:32 GMT
keep-alive:
timeout=60

REQUEST HEADDERS:
accept:
*/*
accept-encoding:
gzip, deflate, br, zstd
accept-language:
ru,ru-RU;q=0.9
access-control-request-headers:
content-type
access-control-request-method:
POST
cache-control:
no-cache
connection:
keep-alive
host:
localhost:21001
origin:
http://localhost:5173
pragma:
no-cache
referer:
http://localhost:5173/
sec-fetch-dest:
empty
sec-fetch-mode:
cors
sec-fetch-site:
same-site
user-agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
< /code>
Заголовки ответов почтальона: < /p>
Vary Origin
Vary Access-Control-Request-Method
Vary Access-Control-Request-HeadersContent-Length 0
Date Sat, 08 Mar 2025 08:59:19 GMT
Keep-Alive timeout=60
Connection keep-alive
< /code>
URL -адрес запроса верен, я попробовал различные параметры для отправки Fetch - он не помогает, сериализует тело: json.stringify (requestData) в классе DTO Весной, кажется, правильным. CORS со всеми другими методами и от других контроллеров, и от этого работает, и все в порядке, но я уже испортился с этим методом, и я просто не понимаю, что здесь не так. И я не использую весеннюю безопасность. Кроме того, все пути URL -адреса верны, данные также правильно установлены в теле на фронте, DTO на бэкэнд также кажется правильным, HTTPSession также принимает данные правильно, но это не проблема. Те, кто знает, помощь.
Необходимо, чтобы метод не входил в подъем, как будто Cors заблокировал этот метод.

Подробнее здесь: https://stackoverflow.com/questions/794 ... ue-to-cors

Вернуться в «JAVA»