axios在后端返回401时,获取不到和返回的状态码问题

时间:2025-03-20 18:17:09

在axios中爬过的坑

项目是后端采用的grails + spring cloud + gorm + es等插件做的, 前端采用的是element + axios + vue等,身份认证采用的是spring cloud oauth2.0 . 开发采用的是gradle搭建,语言使用的是groovy
在搭完框架后,正常流程postman都能跑的通,但是如果使用 axios就会遇到跨域问题
然后就解决吧 首先是preflight被禁的问题:
首先是webSecureAdapter这里

class WebSecure extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ().requestMatchers(new RequestMatcher() {
                @Override
                boolean matches(HttpServletRequest request) {
                    return (request)
                }
            }).permitAll()
          //.and()其他的内容
    }
}

然后发现问题还是没解决 由于认证中心和资源在同一个项目上,暂时未拆分所以 ResourceServerConfigurerAdapter 这里也需要配置

class ResourceConf extends ResourceServerConfigurerAdapter {
@Override
    public void configure(HttpSecurity http) throws Exception {
        ()
        .requestMatchers(new RequestMatcher() {//preflght permitAll 
                    @Override
                    boolean matches(HttpServletRequest request) {
                        return (request)
                    }
                }).permitAll()
}

好了 ,到这里数据访问的跨域已经解决完成了
但是身份认证的时候也是要跨域的,而且我们的返回数据有部分内容是在header中的,这个在使用spring的框架时,会将其中的header替换掉,继续修改
找了半天,终于找到一个将spring Boot的Filter的修改

private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        ("*"); // 1 设置访问源地址
        ("*"); // 2 设置访问源请求头
        ("GET"); // 3 设置访问源请求方法
        ("POST");
        ("DELETE");
        ("PUT");
        ("PATCH");
        ("Content-Range")//这里是需要额外配置的header内容
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        ("/**", buildConfig()); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }

好了,到这里好像已经全部配置完成了,数据能正常的访问,接口也都能正常的请求了,….
但是,在使用axios的时候,如果我们使用的token过期,或者token出错的时候,在浏览器能获取401 ,但是axios死活获取不到正常的返回码,找了一堆的源码,可以确定在axios中处理返回结果的位置
在axios 的lib/adapter/中

request[loadEvent] = function handleLoad() {
      if (!request || ( !== 4 && !xDomain)) {
        return;
      }

      // The request errored out and we didn't get a response, this will be
      // handled by onerror instead
      // With one exception: request that using file: protocol, most browsers
      // will return status as 0 even though it's a successful request
      if ( === 0 && !( && ('file:') === 0)) {
        return;//注意这里,这里如果遇到上述的401/403等问题,直接返回,导致我们的axios不能取到返回码
      }

      // Prepare the response
      var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(()) : null;
      var responseData = ! ||  === 'text' ?  : ;
      var response = {
        data: responseData,
        // IE sends 1223 instead of 204 (/mzabriskie/axios/issues/201)
        status:  === 1223 ? 204 : ,
        statusText:  === 1223 ? 'No Content' : ,
        headers: responseHeaders,
        config: config,
        request: request
      };

      settle(resolve, reject, response);

      // Clean up request
      request = null;
    };

同时前端会报错 ,出现跨域问题, 再次整理后端代码,终于发现了WebSecurityConfigurerAdapter中

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    ...
        .csrf().disable();//这里同上面是相同的位置
    }

这里的csrf被禁用后,如果使用跨域,就导致axios不能获取正常
将这里修改为

()
...
.and().cors()

好了 这时候,如果token超时或者使用不正确的token的时候 就能正常的返回了