在设置了 headers 请求头中的 Authorization 后出现了这个问题
请求异常
Failed to load http://host:port/auth/user/updatePassword: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
JavaScript 代码
// 修改密码
var fd = new FormData()
fd.append('password', '123456789')
fetch(ctx + '/auth/user/updatePassword', {
method: 'post',
credentials: 'include',
headers: {
'Authorization': '39058cb8ec7ee5bde4e8813857a5e6591edf5da2eb997ba8416cf711d083c46ea94a3344f1d8670eaa7a8896ac71e6fdbe90c75b1c579fd52368c82f44777473'
},
body: fd
})
.then(res => res.json())
.then(json => console.log(json))
Java 处理跨域的代码
@Configuration
public class CorsConfig {
@Bean
public OncePerRequestFilter corsFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//允许所有来源
String allowOrigin = "*";
//允许以下请求方法
String allowMethods = "GET,POST,PUT,DELETE,OPTIONS";
//允许以下请求头
String allowHeaders = "Content-Type,X-Token";
//允许有认证信息(cookie)
String allowCredentials = "true";
String origin = request.getHeader("Origin");
//此处是为了兼容需要认证信息(cookie)的时候不能设置为 * 的问题
response.setHeader("Access-Control-Allow-Origin", origin == null ? allowOrigin : origin);
response.setHeader("Access-Control-Allow-Methods", allowMethods);
response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
filterChain.doFilter(request, response);
}
};
}
}
请问上面的代码有什么问题么?为什么明明处理过了结果还是会出现跨域问题呢?
添加回答
举报
0/150
提交
取消