私は数時間前からアプリで何らかの認証コンポーネントを実装しようとしていましたが、まだ何か起こっていることは分かりません。反応とフェッチを使用してCookieを送信しようとしています
基本的に、私は証明書が働いていた場合、トークンと私にcookie
バックを送信する、私のAPI
にいくつかのcredentials
を含むPOST request
を送りたいです。その後、私のAPIへの今後のすべてのリクエストのヘッダーにクッキーを含める必要があります(私はこれが自動であると信じていました)。
server.js(私のAPIは、JSONファイルで、今のモックアップです)
...
app.post('/api/login', jsonParser, (req, res) => {
fs.readFile(ACCOUNTS_FILE, (err, data) => {
if (err) {
console.error(err);
process.exit(1);
}
const accounts = JSON.parse(data);
const credentials = {
email: req.body.email,
password: req.body.password,
};
var token = null;
for (var i = 0; i < accounts.length; ++i) {
const account = accounts[i];
if (account.email === credentials.email
&& account.password === credentials.password) {
token = account.token;
break;
}
}
if (token) {
res.setHeader('Set-Cookie', `access_token=${token}; Secure; HttpOnly;`);
res.json({ token });
} else {
res.json({ token: null });
}
});
});
...
app.js
...
handleConnection(e) {
e.preventDefault();
const email = this.state.email.trim();
const password = this.state.password.trim();
if (!email && !password) {
return (false);
}
fetch(loginUrl, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
credentials: 'include',
},
body: JSON.stringify(this.state),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.warn(error);
});
return (true);
}
...
今console.log(data)
はいつも私のトークンを表示します(または私の資格情報が間違っている場合はnull)、クッキーは機能しません。
私はSet-Cookie
ヘッダーを受け取りますが、まだ私のページにはクッキーはありません。
そして、私はクッキーを取得するために管理していても、私はdocument.cookie = "access_token=123";
を使用してクッキーを作成し、要求を再送信しようとすると、それはjQueryのAjaxcallの場合と同様に、私のクッキーは私のヘッダーに行かない:
here私はcredentials: 'include'
を追加すると、残念ながらそれはなかったと書いてあります。
私はここで何が欠けていますか?
ありがとうございます!
はい、資格情報:「same-起源は非常にうまく機能します。このコードを共有してくれてありがとう。 @Alessio Santacroce。 –
。クッキー値にアクセスする方法は? –