1. axios 添加请求拦截器
// 添加请求拦截器
http.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
const token = Cookies.get("token");
if(token){
token?config.headers.token=token:null;
}
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
解释:从cookie里面获取到token的值,并在发起请求之前添加到请求头里面
记得添加 js-cookie 依赖
2. 后端解决添加自定义请求头后出现的跨域问题
@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Token,Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
}
解释: 在 Access-Control-Allow-Headers 里面添加你自己自定义的请求头,我的是token,则添加Token,记得大写