express使用res.cookie无法设置cookie

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和发送

clipboard.png

clipboard.png

clipboard.png

但是重点是 在浏览器的cookie栏里并没有任何的cookie,而且使用document.cookie也是没有任何的cookie,不管实在node服务的3000端口下,还是在8080端口下都是没有任何cookie

clipboard.png

clipboard.png

clipboard.png

请问这是什么原因??

阅读 13.6k
3 个回答

访问的时候不要使用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:

新手上路,请多包涵

用fetch发请求需要加上credentials : 'include' 才能保存cookie,被坑好久

我也碰到过和你一样的问题最后我的解决方法是

在客户端请求里,加入 withCredentials: 'include'
图片描述

在express的app.js里, cors的配置如图
图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题