繁体   English   中英

获取响应未设置浏览器cookie

[英]Fetch Response is not setting browser cookie

我正在使用fetch API在浏览器中设置cookie。 这是我的请求对象

fetch('/auth',{
      method:'POST',
      headers:{
        'Accept':'application/json',
        'Content-Type':'application/json'
      },
      body: JSON.stringify({
        username:this.state.username,
        password: this.state.password,
        email: this.state.email
      })
    })
    .then(function(response){
      console.log(response)
    })
    .catch(function(err){
      console.log(err)
    })

在服务器端

db.one('insert into account(username,password,email) values ($1,$2,$3) returning * ',[req.body.username,hash,req.body.email])
    .then((result) => {
      console.log('successfully registered: ',result)
      const id_token = jwtSign(result)
      console.log('id_token: ',id_token)
      res.cookie('id_token',JSON.stringify(id_token),{ expires: new Date(Date.now() + (24 * 60 * 60 * 1000 * 30 * 12 * 10)), httpOnly: true })
      res.send({'id_token':id_token})
    })
    .catch((err) => {
      console.log('There was an error: ',err.message)
      res.send(JSON.stringify(err.message))
    })

响应实际上具有SET_COOKIE标头

Set-Cookie:id_token=%22eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTMsInVzZXJuYW1lIjoia2oiLCJpYXQiOjE0Njg2MDk1Njl9.6w46UCTQwpQ4OIiwj-Ae54LLtYUrUgKjMKHJtepkiZk%22; Path=/; Expires=Sun, 24 May 2026 19:06:09 GMT; HttpOnly

但是,我无法在chrome中的resources选项卡中找到cookie。 有人遇到过这个问题吗? 我不确定我哪里出错了

根据提取文档,您必须将credentials设置为same-origininclude

这是docs的例子:

fetch('/users', {
   credentials: 'same-origin'
})

它非常奇怪..但如果我强制获取导航到另一个页面,cookie就会存储

  fetch('/auth',{
      method:'POST',
      headers:{
        'Accept':'application/json',
        'Content-Type':'application/json'
      },
      body: JSON.stringify({
        username:this.state.username,
        password: this.state.password,
        email: this.state.email
      })
    })
    .then(function(response){
      console.log(response)
      window.location = '/'
    })
    .catch(function(err){
      console.log(err)
    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM