我正在 Vue.js 中使用 axios 库开发一个项目。我将 token 信息添加到使用 aixos 创建的请求的 header 参数中。但是当我尝试在 Web 服务中读取此 header 时,授权信息返回 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
最佳答案
我按如下方式解决了这个问题:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().disable()
.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
.and()
.csrf().disable();
}
关于javascript - 使用axios创建post请求后,header值在服务器端返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62003998/