[英]How do I prevent a CORS policy error when posting from JS UI to Java API
My front end application gives this error:我的前端应用程序给出了这个错误:
Access to XMLHttpRequest at 'http://localhost:9025/customer/registerDocs/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
CORS 策略已阻止从源“http://localhost:3000”访问“http://localhost:9025/customer/registerDocs/”处的 XMLHttpRequest:确实如此没有 HTTP 正常状态。
when this is called:当这被称为:
updateDocsStatus() {
return ApiService.postData('http://localhost:9025/customer/registerDocs');
}
This is the controller method in the API:这是API中的controller方法:
@PostMapping(value = Constants.REGISTER_DOCS_PATH,
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseStatus(HttpStatus.OK)
public void registerUserForDocs(HttpServletRequest request){
String username = securityService.getUsername(request);
customerHelper.registerCustomerForEdocs(username);
}
I can't help feel like the issue is something on the front end.我不禁觉得问题出在前端。 Am I missing anything obvious here?
我在这里遗漏了什么明显的东西吗?
this is what i use, probably best to use this with a specific development profile这就是我使用的,可能最好将其与特定的开发配置文件一起使用
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedMethods("*")
.allowedOrigins("http://localhost:3000")
.allowedHeaders("*");
}
}
If you're using Spring Security, CORS can be disabled for all paths (not best practice) by adding the follow bean如果您使用 Spring 安全性,则可以通过添加以下 bean 为所有路径禁用 CORS(不是最佳实践)
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}
Or you can fine tune to the POST method and your specific documentation path (customer/registerDocs)或者您可以微调到 POST 方法和您的特定文档路径 (customer/registerDocs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.