![](/img/trans.png)
[英]Chrome get Set-cookie header but doesnt put it in a new requests
[英]Cookies don't get set in chrome via `Set-Cookie` Header
這些是我從 API ( /login
) 返回的標頭:
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 354
Content-Type: application/json; charset=utf-8
Date: Sun, 21 Mar 2021 19:34:19 GMT
ETag: W/"162-9yg5khk3mdMK+w5SIteR+26LIrw"
Keep-Alive: timeout=5
Set-Cookie: refresh_token=<INSERT REFRESH_TOKEN HERE>; Max-Age=2592000; Expires=Tue, 20 Apr 2021 19:34:19 GMT; HttpOnly
X-Powered-By: Express
這是 Express 后端中的代碼:
app.post('/login', cookieMiddleware, async (req, res) => {
try {
console.log('login now happening');
if (!req.body.code) throw new Error('no code was provided.');
const code = req.body.code;
const data = await fetchToken(
code,
CREDENTIALS.REDIRECT_URI,
CREDENTIALS.CLIENT_SECRET,
CREDENTIALS.CLIENT_ID,
);
res.cookie('refresh_token', data.refreshToken, {
httpOnly: true,
maxAge: 30 * 24 * 60 * 60 * 1000,
});
res.status(200).json(data);
res.end();
return;
} catch (err) {
res.status(500);
res.end();
return;
}
});
(我也嘗試將域設置為localhost
和所有可以想象的path
)
這是cookieMiddleware
:
export const cookieMiddleware = (req: Request, res: Response, next: NextFunction): void => {
const cookies = req.cookies;
console.log('Cookies: ', JSON.stringify(cookies));
const signedCookies = req.signedCookies;
console.log('Signed Cookies: ', JSON.stringify(signedCookies));
next();
};
在 Chrome 中,cookie 不會顯示,即使我將其設置為非httpOnly
。
我總是從中間件的控制台中得到這個:
Cookies: {}
Signed Cookies: {}
編輯:我現在已經用 Postman 對其進行了測試,它在那里工作,但與 chrome/通過前端的結果相同。
我已經在下面寫了答案,這應該可以解決所有問題。
問題是cors
和fetch
-api。
要設置 cookies 您需要在前端執行此操作:
fetch('<DOMAIN>/<PATH>',
{
...
credentials: 'include',
mode: 'cors'
}
)
這在后端:
app.use(
cors({
credentials: true,
origin: '<DOMAIN>'
})
)
但是您必須為后端提供完整的來源 URL ,例如:
您的前端在localhost:3000
上運行,而您的后端在 * localhost:8080
** 上運行。 這將是您的前端代碼:
fetch('http://localhost:8080/login', {
...
credentials: 'include',
mode: 'cors'
...
}
)
那么這將是后端代碼:
app.use(
cors:({
credentials: true,
origin: 'http://localhost:3000'
})
)
使用相同的方法,您可以將 Cookie 發送回您的 API。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.