服务端 express localhost:3000
前端 axios localhost:3001
为解决跨域,所以后端设置了cors策略,但是因为同源策略的限制,跨域时无法使用cookie
res.header("Access-Control-Allow-Origin", "*");
所以需要在前端的请求头中设置 withCredentials:true
来进行cookie传输的跨域。
const server = axios.create({
baseURL: 'http://localhost:3000/api/',
timeout: 1000,
withCredentials: true, // 跨域请求时发送Cookie
});
后端也需要对cors进行配置
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3001");//访问的主机名称
res.header('Access-Control-Allow-Credentials','true'); //是否支持cookie跨域
res.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");//允许以下方法进行跨域请求
next();
});
此时我们还可以根据请求主机,设置cors允许主机名来达到所有测试皆能进行跨域
res.header("Access-Control-Allow-Origin", req.headers.origin);