未在浏览器中设置 Cookie

Cookie not being set in browser

我正在尝试设置一个包含我的授权令牌的 cookie。我可以看到它在响应 header set-cookie: xxxxxx 中返回,但无论出于何种原因,浏览器都没有存储 cookie。

在我的 React 前端 http://app1.dev:3001 我正在这样调用 POST api:

return axios.get(
  `${apiUrl}/info`,
  { withCredentials: true }
)
.then(res => res.data)
.catch(console.error)

我在 http://localhost:3000

上有一个简单的 Koa 服务器 运行
const Koa = require("koa")
const Router = require("koa-router")
const bodyParser = require("koa-bodyparser")
const cors = require("@koa/cors")
const axios = require("axios")
const env = require("./env")
const KeyGrip = require("keygrip")

const app = new Koa()
const router = new Router()
const port = env("port")

const keyList = ["xxxxxxx",]
app.keys = new KeyGrip(keyList, "sha256")

router.get("/info", ctx => {
  console.log('req', ctx.req)
  ctx.cookies.set("token", "test_token", { signed: true, httpOnly: true })
  ctx.body = { ok: true }
})

const corsOptions = {
  origin: ctx => ctx.request.header.origin,
  credentials: true
}

app
  .use(cors(corsOptions))
  .use(bodyParser())
  .use(router.routes())
  .use(router.allowedMethods())

app.listen(port, () => console.info(`Listening on port ${port}`))

我怀疑它没有被设置,因为它是跨域的。当我在前端使用 http://localhost:3001 时,cookie 设置正常。

为什么没有在浏览器中设置 cookie?任何帮助将不胜感激。

当你使用 http://localhost:3001 作为前端时,你的前端和后端服务器共享同一个域(甚至在不同的端口),所以你可以看到通过请求设置的 cookie 到你的后端服务器(和所以链接到后端服务器域)。

当您使用不同的域时,您只是看不到 cookie,因为开发工具附加到属于另一个域的页面。但 cookie 已保存并将随后续请求发回。