根本原因:
带 cookie 的跨域请求, 需要前端明确设置,后台也明确设置可以请求的ip地址
前端请求设置
引入axios的页面中增加默认配置项 withCredentials
import axios from "axios"; axios.defaults.withCredentials = true;
请求时设置 (withCredentials: true 说明是带 cookie 请求)
axios.post('path', {data}, { headers: { "Content-Type": "application/json;charset=utf-8" }, withCredentials: true, })
后台设置
允许访问的IP(明确的写明接收的请求 IP)
response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8010");
还需要增加允许 Credentials 请求的字段
response.setHeader("Access-Control-Allow-Credentials", "true");
服务器设置允许多个ip访问
没经过测试,使用请自测
Java服务器设置
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
String [] allowDomain= {"http://127.0.0.1:1808","http://192.168.1.178"};
Set<String> allowedOrigins= new HashSet<String>(Arrays.asList(allowDomain));
String originHeader=((HttpServletRequest) req).getHeader("Origin");
if (allowedOrigins.contains(originHeader)) {
response.setHeader("Access-Control-Allow-Origin", originHeader);
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, x-requested-with");
response.setHeader("Access-Control-Allow-Credentials", "true");
}
chain.doFilter(req, res);
}
Nodejs服务器
if( req.headers.origin == 'https://www.google.com' || req.headers.origin == 'https://www.baidu.com' ){
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header('Access-Control-Allow-Methods', 'POST, GET');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
res.header('Access-Control-Allow-Headers', 'Content-Type');
}