通过CORS跨域时,浏览器不会自动带上cookie。想要传递cookie,需要客户端与服务端共同设置。
需要解决两个方面的问题
- 1.服务端需要设置 Access-Control-Allow-Origin
该字段表明服务端接收哪些域名的跨域请求,如果值为 * 号,表示接收任意域名的跨域请求。
当需要传递cookie时,Access-Control-Allow-Origin 不能设置为 * 号,必须为具体的一个域名。
同时,服务端需要设置 Access-Control-Allow-Credentials 为 true。表示服务端同意发送cookie。
const http = require('http');
const url = require('url');
const fs = require('fs');
const tool = require('./tool.js');
http.createServer((req, res) => {
let pathName = url.parse(req.url).pathname;
console.log('请求地址', req.url);
if (pathName === '/getMessage') {
// res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Content-Type', 'application/json');
res.write();
res.end();
} else {
res.end();
}
}).listen(8080);
- 2.客户端需要设置Ajax请求属性withCredentials=true,让Ajax请求都带上Cookie。
对于XMLHttpRequest的Ajax请求
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true; // 携带跨域cookie
xhr.send();
对于JQuery的Ajax请求
$.ajax({
type: "GET",
url: url,
xhrFields: {
withCredentials: true // 携带跨域cookie
},
processData: false,
success: function(data) {
console.log(data);
}
});
对于axios的Ajax请求
axios.defaults.withCredentials=true; // 让ajax携带cookie
当使用fetch发送请求时,需要设置 credentials 为include,如下
fetch('http://localhost:8080/getMessage', {
credentials: 'include'
});