首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取API cookies不可访问?

获取API cookies不可访问?
EN

Stack Overflow用户
提问于 2018-06-05 08:36:25
回答 1查看 4.4K关注 0票数 0

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

代码语言:javascript
复制
  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得到的响应头:

代码语言:javascript
复制
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是我想要设置的。我看过其他关于这方面的文章,但它们似乎没有解决我的特定问题。有什么建议吗?

编辑:

代码语言:javascript
复制
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))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-05 09:39:26

我认为header对象中有credentials,但它不是标头。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50690505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档