axios post 403 forbidden but postman works

Viewed 3397

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

Server: Spring Boot localhost:8080

Web: Vue.js + Axios localhost: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 func:

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

then,in MSEdge localhost:80/ :

403 forbidden

however in postman it works well:

postman works

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

1 Answers

Ok I HAVE SOLVED IT NOW!!!!

that's because I've configured CORS

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

and

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

Reason:

  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)。

so the right code is:

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

and

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

;P

Related