【发布时间】: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