简体   繁体   English

Cookies 不要通过“Set-Cookie”在 chrome 中设置 Header

[英]Cookies don't get set in chrome via `Set-Cookie` Header

I'm having some trouble setting a cookie through Express.JS in my frontend (Next.JS).我在前端(Next.JS)中通过 Express.JS 设置 cookie 时遇到了一些问题。

These are the Headers I get back from the API ( /login ):这些是我从 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

This is the code in the Express Backend:这是 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;
    }
});

(I've also tried setting the domain to localhost and the path to everything imaginable) (我也尝试将域设置为localhost和所有可以想象的path

And this is the cookieMiddleware :这是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();
};

In Chrome the cookie doesn't show up, even if I set it as non- httpOnly .在 Chrome 中,cookie 不会显示,即使我将其设置为非httpOnly

And I always get this in the Console from the Middleware:我总是从中间件的控制台中得到这个:

Cookies:  {}
Signed Cookies:  {}

EDIT: I've now tested it with Postman and there it works, but still the same result with chrome/via the frontend.编辑:我现在已经用 Postman 对其进行了测试,它在那里工作,但与 chrome/通过前端的结果相同。

EDIT 2:编辑2:

I've written the Answer down below, this should fix everything.我已经在下面写了答案,这应该可以解决所有问题。

I've found the answer我找到了答案

The Problem was cors and the fetch -api.问题是corsfetch -api。

To set cookies you need to do this in the frontend:要设置 cookies 您需要在前端执行此操作:

fetch('<DOMAIN>/<PATH>',
    {
        ...
        credentials: 'include',
        mode: 'cors'
    }
)

and this in the backend:这在后端:

app.use(
    cors({
        credentials: true,
        origin: '<DOMAIN>'
    })
)

BUT YOU MUST GIVE THE BACKEND THE FULL ORIGIN URL , for example:但是您必须为后端提供完整的来源 URL ,例如:
Your Frontend runs on localhost:3000 and your Backend runs on * localhost:8080 **.您的前端localhost:3000上运行,而您的后端在 * localhost:8080 ** 上运行。 This would be your Frontend Code :这将是您的前端代码

fetch('http://localhost:8080/login', {
        ...
        credentials: 'include',
        mode: 'cors'
        ...
    }
)

Then this would be the Backend Code :那么这将是后端代码

app.use(
    cors:({
        credentials: true,
        origin: 'http://localhost:3000'
    })
)

With the same Method you can send the Cookie back to your API.使用相同的方法,您可以将 Cookie 发送回您的 API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM