1.问题描述:
前台vue项目中需要在request_header中传cookie给后台
但是控制台报错如下;
Access to XMLHttpRequest at ‘http://192.168.0.230:9800/v1/user/wwwlogin’ from origin ‘http://192.168.0.230:8888’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
2.问题分析:
- 后台的跨域配置Access-Control-Allow-Origin不能使用通配符 ‘*’;
- 请求的origin和后台设置的origin不一致。
3.问题解决:
跨域配置修改:
通过动态的获取origin,可解决此问题
res.addHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
springboot完整的跨域配置:
package com.cxstar.dao.data.config;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 单机测试时如果有跨域问题,就用这个Filter解决,把@Component前的注释移除即可
* 如果是在微服务中,跨域问题在网关层进行了解决,服务没必要再次进行处理,把@Component注释掉即可
*/
@Component
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN,customercoderoute,authorization,conntectionid,Cookie");
if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}