Node.js 获取API cookie不可访问?
我有一个React应用程序,它向运行passportjs进行身份验证的express后端发出REST POST请求。我正试图使用fetchapi发送POST请求,但当我这样做时,我不知道如何访问从服务器发送回来的cookie。我看到响应头显示了我希望在devtools中使用的cookie,而且当我使用常规html时,它会工作,cookie会自动发送并持久化。我的问题是,在使用fetchapi时,我无法持久保存cookie,因为我不知道在收到cookie后如何访问它Node.js 获取API cookie不可访问?,node.js,reactjs,cookies,passport.js,fetch,Node.js,Reactjs,Cookies,Passport.js,Fetch,我有一个React应用程序,它向运行passportjs进行身份验证的express后端发出REST POST请求。我正试图使用fetchapi发送POST请求,但当我这样做时,我不知道如何访问从服务器发送回来的cookie。我看到响应头显示了我希望在devtools中使用的cookie,而且当我使用常规html时,它会工作,cookie会自动发送并持久化。我的问题是,在使用fetchapi时,我无法持久保存cookie,因为我不知道在收到cookie后如何访问它 login () {
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是我要设置的。我看过其他关于这方面的文章,但它们似乎没有解决我的特定问题。有什么指导吗
编辑:
我认为您在header对象中拥有凭据,但它不是header
此外,cookies不是document的属性,而是document.cookie。这样做有效,我还删除了试图手动设置cookies的部分。将凭据放在正确的位置后,会自动设置凭据。谢谢:
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))