我在Spring Boot上遇到了CORS问题。Get请求使用用于CORs的Spring配置(使用WebMvcConfigurer)。POST请求不起作用。
我不仅尝试了Java配置,还尝试了注释(@CrossOrigin())和过滤器(排序为HIGHEST_PRECEDENCE)。对于Get请求,注释似乎永远不会为我的-even工作。
我的CORS过滤器(复制粘贴22kar的答案):Spring Boot : CORS Issue
我的WebMvcConfigurer:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:3000");
registry.addMapping("/greeting-posttest").allowedOrigins("http://localhost:3000");
// .allowedHeaders("Access-Control-Request-Method", "Origin", "Access-Control-Request-Headers")
// .allowedMethods("POST", "OPTIONS", "HEAD", "GET", "PATCH")
// .exposedHeaders("Access-Control-Allow-Origin");
}
};
}
我的注释驱动的cors:
// @CrossOrigin(origins = "http://localhost:3000")
@PostMapping("/greeting-posttest")
public Greeting greetingPostTesting(@RequestBody String content) {
System.out.println("==== in greeting post ====");
Greeting newGreeting = new Greeting(counter.incrementAndGet(), content);
return newGreeting;
}
发出请求的JS (来自react-redux应用程序):
export function apiCall(method, path, data){
return new Promise((resolve, reject)=>{
return axios.post("http://localhost:8080/greeting-posttest",{content: "POSTING!"}, config).then(res=> {
console.log("successful");
console.log(res);
return resolve(res.data)
}).catch(err => {
console.log("caught in apiCall")
console.log(err);
return reject(err.response);
})
})
}
const config={
headers: {
'Origin': 'http://localhost:3000',
// 'X-Requested-With': 'http://localhost:3000',
'Access-Control-Request-Method' : 'POST, OPTIONS',
'Access-Control-Request-Headers': 'access-control-allow-origin'
}
}
编辑:浏览器Devtools响应:
Forbidden header name: Origin
Forbidden header name: Access-Control-Request-Method
Forbidden header name: Access-Control-Request-Headers
Axios响应:
Error:"Network Error"
据我所知,Axios的响应是,当Axios不能建议错误状态代码时,就会给出网络错误。
=
我的后台:https://github.com/eeasuper/testing123
我的前端:https://github.com/eeasuper/practiceNaverMockingWeb
我在前端的apicall:https://github.com/eeasuper/practiceNaverMockingWeb/blob/master/src/services/api.js
(前端仓库中的后端文件与本文无关。)
发布于 2019-01-30 13:50:58
有了Spring Security,我在云上的React-Redux项目中使用了它,遵循这个post。此外,按照用户bvulaj在此github link底部给出的说明,使我的React项目在本地主机上工作。我的react版本是16.8.6,我的Spring版本是4.0.0。
https://stackoverflow.com/questions/54416874
复制相似问题