问题描述
我正在尝试设置一个其中包含我的身份验证令牌的cookie。我可以看到它在响应标头 set-cookie:xxxxxx
中返回,但是由于某种原因,浏览器没有存储cookie。
I am trying to set a cookie which has my auth token in it. I can see it being returned in the response header set-cookie: xxxxxx
but for whatever reason, the browser is not storing the cookie.
在我的反应前端 http://app1.dev:3001
我正在这样进行POST api调用:
On my react front end http://app1.dev:3001
I am making an POST api call as such:
return axios.get(
`${apiUrl}/info`,
{ withCredentials: true }
)
.then(res => res.data)
.catch(console.error)
我有一个运行在 http:// localhost:3000
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时,设置得很好。
I suspect it is not being set because it is cross domain. when I use http://localhost:3001
for my front end the cookie gets set fine.
为什么没有在浏览器中设置cookie?任何帮助将不胜感激。
Why are the cookies not being set in browser? Any help would be greatly appreciated.
推荐答案
使用 http:// localhost:3001
对于前端,前端和后端服务器共享相同的域(即使位于不同的端口上),因此您可以看到对后端服务器的请求所设置的cookie(并因此链接到后端服务器域)。
When you use http://localhost:3001
for the frontend, your frontend and backend servers share the same domain (even being on different ports), so you can see the cookie set by a request to your backend server (and so linked to backend server domain).
当您使用其他域时,由于开发工具已附加到属于另一个域的页面上,因此您根本看不到Cookie。但是Cookie已保存,并将随后续请求一起发送回去。
When you use different domains, you just can't see the cookie as dev tools are attached to a page that belongs to another domain. But the cookie is saved and will be sent back with subsequent requests.
这篇关于未在浏览器中设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!