Spring Boot Cors问题:尝试了所有操作,但POST无法正常工作

时间:2019-01-29 08:39:36

标签: ajax spring-boot post cors

我在Spring Boot上遇到了CORS问题。 Get Request使用Spring的COR Java配置(使用WebMvcConfigurer)工作。 POST请求无效。

我不仅尝试了Java配置,还尝试了批注(@CrossOrigin())和过滤器(已排序为HIGHEST_PRECEDENCE)。注释似乎对我来说从来没有用过,即使是对于“获取请求”也是如此。

我的CORS过滤器(复制并粘贴了22kar的答案): Spring Boot : CORS Issue

我的WebMvcConfigurer:

cat <<EOF >> /home/ec2-user/.bashrc
export NVM_DIR="/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
EOF

我的注释驱动的核心:

@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");
        }
    };
}

发出请求的JS(来自react-redux应用):

//    @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;
}

编辑: 浏览器Devtools响应:

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'
  }
}

Axios响应:

Forbidden header name: Origin
Forbidden header name: Access-Control-Request-Method
Forbidden header name: Access-Control-Request-Headers

据我所知,关于Axios的响应,当Axios无法提示错误状态代码时,就会给出网络错误。

===================

我的后端:https://github.com/eeasuper/testing123

我的前端:https://github.com/eeasuper/practiceNaverMockingWeb

我在前端的apicall:https://github.com/eeasuper/practiceNaverMockingWeb/blob/master/src/services/api.js

(前端存储库中的后端文件与该帖子无关。)

1 个答案:

答案 0 :(得分:0)

借助post,我使用Spring Security在云上处理了我的React-Redux项目。此外,按照github link底部用户bvulaj给出的说明,我的React项目在localhost上工作。我的React版本是16.8.6,我的Spring版本是4.0.0。