router.post('/login', (req, res, next) => {
const {userName, userPwd} = req.body;
const params = {
userName,
userPwd,
};
User.findOne(params).then((doc) => {
if (doc) {
res.cookie('userId', doc.userId, {
domain: 'http://127.0.0.1:8080',
path: '/',
maxAge: 5000000,
});
res.json({
status: 0,
msg: '',
data: doc.userName,
});
} else {
throw new Error('密码或者用户名错误');
}
}).catch((err) => {
res.json({
status: 1,
msg: err.message,
data: null,
});
});
});
router.get('/addressList', (req, res, next) => {
console.log('addressList', req.cookies);
const {userId} = req.cookies;
User.findOne({userId})
.then((doc) => {
if (doc) {
res.json({
status: 0,
msg: '',
data: doc.addressList,
})
} else {
throw new Error('没有该用户');
}
}).catch((err) => {
res.json({
status: 1,
msg: err.message,
data: null,
});
})
});
cors设置
app.use(cors({
origin: 'http://127.0.0.1:8080',
credentials: true,
}));
app.use(cookieParser());
前端代码
<script>
function list() {
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "http://localhost:3000/users/addressList");
xhr.setRequestHeader("x-node", "nodejs");
xhr.send(data);
}
function login() {
var data = "userName=%E9%AC%BC%E5%89%91%E5%A3%AB&userPwd=665533";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://localhost:3000/users/login");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("x-custom", "abcd");
xhr.send(data);
}
login();
setTimeout(() => {
list();
}, 3000 )
</script>
首先调用login,然后再login里面设置cookie然后调用list。在服务端也是获得了cookie,从浏览器NetWork也是有cook被set和发送
但是重点是 在浏览器的cookie栏里并没有任何的cookie,而且使用document.cookie也是没有任何的cookie,不管实在node服务的3000端口下,还是在8080端口下都是没有任何cookie
请问这是什么原因??
访问的时候不要使用127.0.0.1来,用域名访问就可以了。有的浏览器在localhost的时候,会拒绝生成cookies。我之前遇到过一次这样的问题,后面用ip访问就没问题了。
something that wasn't made clear to me here and totally confused me for a while was that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie! instead for localhost you should use false.
to make your code work on both localhost and a proper domain, you can do this: