客户端发起ajax跨域请求时, 为什么服务器不能向客户端设置cookie?

新手上路,请多包涵

我在 http://localhost:63343/ 的客户端向服务器 http://localhost:4001/test 发起跨域请求.

  • 客户端部分代码

    const result = await axios.get('http://127.0.0.1:4001/test',{withcredentials:true})
  • 服务器部分代码

    app.get('/test', (req, res) => {
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost:63343')
      res.setHeader('Access-Control-Allow-Credentials', 'true')
      let theme = {theme: 'silence'}
      res.cookie('person', JSON.stringify(theme), {maxAge: 1000 * 60, httpOnly: false})
      // ...
    })

成功实现跨域请求后, 却无法获得服务器的cookie, 检查响应头发现响应头里携带有set-cookie, 但是浏览器application中没有对应的cookie

Set-Cookie: person=%7B%22theme%22%3A%22silence%22%7D; Max-Age=60; Path=/; Expires=Tue, 19 Apr 2022 02:45:21 GMT

请问在ajax跨域请求中如何使客户端能够存储服务器发送的cookie?

阅读 1.9k
2 个回答

Chrome?

SameSite=None; Secure; 二者缺一不可。

截图看看请求的请求头和响应头?

不然,直接试试把请求代码的ip改为localhost?
const result = await axios.get('http://localhost:4001/test',{withcredentials:true})

或者试试在全局设置axios.defaults.withcredentials=true

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