【发布时间】:2021-08-14 09:53:36
【问题描述】:
我使用 React JS 作为前端,Spring boot 作为后端服务。
使用Axios 调用删除服务时出现CORS 错误。在 Rest 控制器类中添加了跨域。
@CrossOrigin(origins = {"http://localhost:3000/"}
谁能帮助解决这个 CORS 问题?
**Error message: Access to XMLHttpRequest at 'http://localhost:8080/testdelete' from origin 'http://localhost:3000' 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.**
我的 ReactJS 代码:
return axios({
method:'DELETE',
url:`http://localhost:8080/testdelete`,
data: data,
headers: {
'Access-Control-Allow-Headers':'Content-Type',
'Access-Control-Allow-Origin': 'http://localhost:3000',
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
'Content-Type': 'application/json'
}
})
这是我的 Spring 启动控制器代码:
@CrossOrigin(origins = {"http://localhost:3000/"},
methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.POST,RequestMethod.OPTIONS})
@RestController
public class TestDelete {
@DeleteMapping("/testdelete")
public ResponseEntity<void> deleteData(@RequestBody Data data) throws Exception {
// logic
}
}
【问题讨论】:
-
请同时添加代码sn-ps。
-
添加代码 sn-p.
-
尝试 @CrossOrigin(origins = {"localhost:3000"}) 代替 @CrossOrigin(origins = {"localhost:3000"}) (不带 / )
-
@Rebai Ahmed - 删除了 '/',放置了 @CrossOrigin(origins = {"localhost:3000"}) 但仍然无法正常工作。
-
检查我的答案,希望对您有所帮助!
标签: reactjs spring-boot cors