admin管理员组文章数量:1405510
I have a backend using Spring and a frontend using React. I already have many controllers and all methods work with current CORS:
@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);
}
}
It's worth noting that I don't use Spring Security. This is my pom:
<dependencies>
<dependency>
<groupId>.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>6.1.4</version>
</dependency>
<dependency>
<groupId>.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.2</version>
</dependency>
<dependency>
<groupId>.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
<scope>provided</scope>
</dependency>
</dependencies>
Now I have this controller and the only method that doesn't work:
Dto and controller method (/edit
doesn't work):
@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) {
thismentService = commentService;
}
@GetMapping("/get-all")
public ResponseEntity<?> getAllComments() {
List<CommentDto> 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();
}
}
The thing is that it is the @PostMapping("/edit")
method that does not work when fetching from the frontend (all other works good, the problem exactly in this)
This is fetch from 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);
}
This method is called by clicking on the button (onClick={handleSendEditCommentData}
)
All data that is put in the body is: commentId
(long
), isPublished
(bool
), are put normally, commentId
is simply an id via props, and isPublished
is a simple bool useState
that is set by the user.
This fetch method always crashes in catch: catch error: Failed to fetch
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
Here two requests are sent, and both of them do not receive a response, in devtools they are marked in red,
FIRST - Status: CORS error, type: fetch
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
SECOND - Status: 401, type: preflight
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
Postman response headers:
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
The request URL is correct, I tried different options for sending fetch - it doesn't help, serializes body: JSON.stringify(requestData) in the DTO class in spring, it seems to be correct. CORS with all other methods and from other controllers and from this one works and everything is fine, but I have already messed around with this method and I just don't understand what is wrong here. And I don't use Spring Security. Also, all URL paths are correct, the data is also set correctly in the body on the frontend, the DTO on the backend also seems to be correct, HttpSession also takes the data correctly, but this is not the problem.
If you need any additional information, please write. And help me solve this problem, I really have already spent a lot of time and am sitting in one place trying to figure it out. Those who know, help.
It is necessary that the method does not go into catch, as if CORS blocked this method.
本文标签: javascriptCannot fetch from Spring backend due to CORSStack Overflow
版权声明:本文标题:javascript - Cannot fetch from Spring backend due to CORS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744899302a2631249.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论