简体   繁体   中英

res.setHeader(“Set-Cookie”, …) is not setting the cookie in Node / Express

I have tried

  res.setHeader(
    "Set-Cookie",
    cookie.serialize("name", "name2", { path: "/", domain: "localhost" })

and

  res.setHeader(
    "Set-Cookie",
    cookie.serialize("name", "name2"))

and I have tried to set the cookie outright with

res.setHeader(
    "Set-Cookie",
    "name=name"})

but no cookie is set when I examine the res, and no cookie is received in my frontend. Everything is run locally. I do not understand why.

如果您只想制作一个cookie,请尝试使用它而不是res.setHeader()

res.cookie('cookieName', 'cookieValue');

I found the answer. When using fetch() from the front end I didn't set the credentials flag to include. When I included the flag it worked instantly.

  return await fetch(
    `url`,
    { credentials: "include" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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