在使用 axios 创建一个post请求后,服务器端的头值会返回null。

问题描述 投票:0回答:1

我正在开发一个项目 轴心 库中的Vue.js。我将token信息添加到我用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个回答
0
投票

我解决了这个问题,具体如下。

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

© www.soinside.com 2019 - 2024. All rights reserved.