【问题标题】:After creating a post request with axios, the header value returns null on the server side用axios创建post请求后,服务端header值返回null
【发布时间】:2020-09-12 04:26:38
【问题描述】:

我正在用 Vue.js 中的 axios 库开发一个项目。我将令牌信息添加到使用 aixos 创建的请求的标头参数中。但是当我尝试在 Web 服务中读取此标头时,授权信息返回 null。

客户端

 let config = {
      headers : {
        'Content-Type': 'application/json',
        'Authorization': token.toString(),
      }
    }
    console.log(token)
    axios.post(baseUrl.base+'api/v1/post', {post},{
      headers : {
        'Authorization' : token.toString(),
        'Content-Type': 'application/json',
      }
    }).then(response => {
        console.log(response)
    })

服务器端 JWTFilter.java

protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            if (isProtectedUrl(request)) {
                String token = request.getHeader("Authorization"); // expected value = Bearer eyc... but return null
                JwtUtil.validateToken(token);
            }

        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }
        filterChain.doFilter(request, response);
    }

CorsConfig.java

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowCredentials(true);
        configuration.addAllowedOrigin("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
Access to XMLHttpRequest at 'localhost:8081/api/v1/post' from origin 'localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

【问题讨论】:

    标签: javascript java spring-boot servlets axios


    【解决方案1】:

    我解决了这个问题如下:

    @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.httpBasic().disable()
                    .cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
                    .and()
                    .csrf().disable();
        }
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2020-12-18
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 2022-01-04
      • 2018-02-23
      相关资源
      最近更新 更多