【问题标题】:axios post 403 forbidden but postman worksaxios 发布 403 被禁止但邮递员工作
【发布时间】:2020-11-02 23:28:57
【问题描述】:

使用 axios post 得到 403 被禁止,但 postman 和 axios 得到所有工作

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

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

Spring Boot CORS 配置:

@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: {
  '/api':{
    target: "http://localhost:8080/",
    changeOrigin:true,
  }},

Axios 函数:

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

Spring Boot 控制器:

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

然后,在 MSEdge localhost:80/ 中:

403 forbidden

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

postman works

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

【问题讨论】:

  • CORS 通常不会返回 403,当它是 CORS 问题时,通常是为了让服务器返回正确的响应,但浏览器会因为缺少 CORS 标头而阻止您查看响应...我可能错了,但你确定这是 CORS 问题吗?
  • 事实上,我不知道发生了什么....我尝试使用没有 args 的新控制器“获取”,效果很好,只是无法发布...(没有有效负载的发布也得到了第403章)
  • 我从你的浏览器上看到的(我看不懂中文)好像是来自axios的请求是发给127.0.0.1:80的,所以代理工作正常吗?
  • 是的,它有效,我尝试使用 post man get 127.0.0.1:80/api/te ,它有效...和 ​​127.0.0.1:8080/api/te 以同样的方式。现在我解决了,看看我的答案,即使我不知道为什么;P
  • 我想我已经找到原因了,看看我的回答。谢谢。

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


【解决方案1】:

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

那是因为我已经配置了 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

【讨论】:

    猜你喜欢
    • 2019-02-28
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 2018-10-20
    相关资源
    最近更新 更多