【问题标题】:Fetch Response is not setting browser cookie获取响应未设置浏览器 cookie
【发布时间】:2016-11-19 02:24:03
【问题描述】:

我正在使用 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。 有没有人遇到过这个问题?我不知道我哪里出错了

【问题讨论】:

    标签: javascript express cookies


    【解决方案1】:

    它很奇怪.. 但是如果我强制 fetch 导航到另一个页面,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)
        })
    

    【讨论】:

    • 这不是SPA的方式。
    【解决方案2】:

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

    这是来自文档的示例:

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

    【讨论】:

    • 此选项在“auth request”和其他“fetch”请求中是必需的。
    猜你喜欢
    • 2020-10-07
    • 2021-07-20
    • 1970-01-01
    • 2019-04-26
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    相关资源
    最近更新 更多