如何在后端的跨域配置中添加对Authorization等请求头的允许
时间: 2024-02-18 22:03:17 浏览: 114
java解决请求跨域的两种方法
在SpringBoot中,可以通过添加一个拦截器来实现对Authorization等请求头的允许。具体步骤如下:
1. 创建一个拦截器类,实现HandlerInterceptor接口,重写preHandle方法。
```java
public class CorsInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, remember-me");
return true;
}
}
```
2. 在WebMvcConfigurer中添加拦截器
```java
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CorsInterceptor());
}
}
```
以上代码会在每个请求的响应头中添加Access-Control-Allow-Headers,其中包括Authorization等请求头,以允许前端发送带有token信息的请求。注意,此方法会允许所有来源的请求,建议在生产环境中限制来源。
阅读全文