axios post 403 被禁止,但邮递员工作 [英] axios post 403 forbidden but postman works

查看:37
本文介绍了axios post 403 被禁止,但邮递员工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 axios post get 403 forbidden 但 postman 和 axios 得到所有工作

use axios post get 403 forbidden but postman and axios get all works

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

Server: Spring Boot localhost:8080

网页:Vue.js + Axios 本地主机:80

Web: Vue.js + Axios localhost:80

Spring Boot CORS 配置:

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 代理表:

Vue.js ProxyTable:

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

Axios 函数:

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

Spring Boot 控制器:

Spring Boot Controller:

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

然后,在 MSEdge 本地主机:80/:

then,in MSEdge localhost:80/ :

403 禁止

但是在邮递员中它运行良好:

however in postman it works well:

邮递员作品

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

I've tried for 3 hours ,and now I'm very tired...

推荐答案

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

Ok I HAVE SOLVED IT NOW!!!!

那是因为我已经配置了 CORS

that's because I've configured 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(请求的页面).
  1. allowedOrigin should be http://localhost:80 , adding '/' in the end is a mistake.
  2. proxyTable.'/api'.changeOrigin:true will just set Host Header to target,NOT set Origin Header to target,this is DIFFERENT from allowedOringins method in SpringBoot CORS CONFIG,your request's origin is still htpp://localhost (the page that request)。

所以正确的代码是:

@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

这篇关于axios post 403 被禁止,但邮递员工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆