禁止axios发布403,但邮递员可以工作

时间:2020-07-13 17:48:53

标签: spring spring-boot vue.js post axios

使用axios帖子被禁止使用403,但邮递员和axios可以完成所有工作

服务器:Spring Boot本地主机:8080

Web:Vue.js + Axios本地主机:80

Spring Boot CORS CONFIG:

@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(1800)
                .allowedOrigins("http://localhost:80/");
    }
}

Vue.js ProxyTable:

proxyTable: {
  '/api':{
    target: "http://localhost:8080/",
    changeOrigin:true,
  }},

Axios功能:

  doLogin(){
    axios({
      method: 'post',
      url: '/api/te',
      data: {
        userNumber: 'hi'
      }
    });

Spring Boot Controller:

@PostMapping("/te")
public String Test(@RequestBody HashMap<String,String> map) {
    return map.get("userNumber");
}

然后,在MSEdge localhost:80 /中:

403 forbidden

但是在邮递员中效果很好:

postman works

我已经尝试了3个小时,现在我很累...

1 个答案:

答案 0 :(得分:0)

好的,我现在已经解决了!!!

那是因为我已经配置了CORS

allowedOrigins("http://localhost:80/");

proxyTable: {
  '/api':{
    target: "http://localhost:8080/",
    changeOrigin:true,
  }},

原因:

  1. allowedOrigin应该为http://localhost:80,最后添加'/'是一个错误。
  2. proxyTable.'/api'.changeOrigin:true只会将Host Header设置为target,而不是将Origin Header设置为target,这与SpringBoot CORS CONFIG中allowedOringins方法的不同,您的请求的源仍然是htpp:// localhost(请求的页面) 。

所以正确的代码是:

@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(1800)
                .allowedOrigins("http://localhost");
    }
}

proxyTable: {
  '/api':{
    target: "http://localhost:8080",
    changeOrigin:true,
  }},

; P