【问题标题】:Fetch API cookies not accessible?获取 API cookie 无法访问?
【发布时间】:2018-11-14 08:59:43
【问题描述】:

我有一个 React 应用程序,它向运行 passportjs 的快速后端发出 REST POST 请求以进行身份​​验证。我正在尝试使用 Fetch API 发送 POST 请求,但是当我这样做时,我不知道如何访问从服务器发回的 cookie。我看到响应标头在 devtools 中显示了我想要的 cookie,而且当我使用常规 html 时它也可以工作,并且 cookie 会自动发送并保留。我的问题是我在使用 Fetch API 时无法保留 cookie,因为我不知道在收到它后如何访问它。

  login () {
    const data = {
      username: this.state.username,
      password: this.state.password
    }

    const options = {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
        credentials: 'include' // tried this too.
        // credentials: 'same-origin'
      }
    }

    fetch('/login', options)
      .then(res => {
        console.log('res', res)
        // cookies.set('connect.sid', document.cookie['connect.sid'])
        console.log(document.cookie['connect.sid'])// undefined
        console.log(res.headers) // empty
        console.log(document.cookies) // undefined
        // cookies.set('connect.sid', res.headers) // need to set this but where is the cookie from server?
      })
      .then(this.clearInputFields.bind(this))
  }

这是我目前通过 FETCH API 获得的响应标头:

HTTP/1.1 200 OK
x-powered-by: Express
content-type: text/html; charset=utf-8
content-length: 14
etag: W/"e-Xft1SGvF5rPEfqfROtKDA2epBao"
set-cookie: connect.sid=s%3ACRnk3A0b0o5T8VSQTVpvTUgW54lO38IJ.skdIbmipmb1CGn6oEQ5KzdS2zGdNiZQrFDwU5cTuy7A; Path=/
date: Tue, 05 Jun 2018 00:32:15 GMT
connection: close
Vary: Accept-Encoding

connect.sid 是我想要设置的。我看过其他关于此的文章,但它们似乎没有解决我的特定问题。有什么指导吗?

编辑:

const options = {
  method: 'POST',
  body: JSON.stringify(data),
  credentials: 'include', // credentials moved to here fixed the issue
  headers: {
    'Content-Type': 'application/json'
  }
}

fetch('/login', options)
  .then(this.clearInputFields.bind(this))

【问题讨论】:

    标签: node.js reactjs cookies passport.js fetch


    【解决方案1】:

    我认为header 对象中的credentials 不是标头。

    另外,cookies 不是document 的属性,而是document.cookie

    【讨论】:

    • 那行得通,我还删除了我尝试手动设置 cookie 的部分。将凭据放在正确的位置后,它们会自动设置。谢谢:)
    猜你喜欢
    • 2021-07-24
    • 2016-02-09
    • 2018-10-10
    • 2016-02-16
    • 2018-01-08
    • 2020-10-09
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    相关资源
    最近更新 更多