我试图通过 axios 请求将 cookie(在浏览器中设置(例如 Edge V102.0.1245.44 或 Firefox V89.0.2))传递到另一台服务器(位于同一主机 = localhost)。我仍然尝试了很多不同的设置,但没有一个起作用。 该cookie似乎存在于快速请求中(
http://localhost:3000/request
)req.headers.cookie
。
参见:
这是我尝试过的一个例子:
发送请求
http://localhost:3000/request
,cookie是之前通过http://localhost:3000/setcookie
设置的:
const express = require('express')
import { Request, Response } from "express"
const axios = require('axios')
const dayjs = require('dayjs')
const app = express()
const port = 3000
app.get('/setcookie', (req: Request, res: Response) => {
const cookieName = 'cookie-name'
const cookieValue = dayjs().format('HH:mm:ss DD.MM.YYYY')
res.cookie(cookieName, cookieValue);
res.send(`Cookie successfully set: ${cookieName}=${cookieValue}`);
});
let content = `Hello world`
app.get('/', (req: Request, res: Response) => {
console.log(req.cookies)
console.log(req.headers.cookie)
res.send(content)
})
app.get('/request', async (req: Request, res: Response) => {
console.log(req.cookies)
console.log(req.headers.cookie)
let url = 'http://localhost:2999'
try {
const result = await axios.get(url, { withCredentials: true })
console.log(result.headers)
}
catch (error) {
console.log(error)
}
res.send(true)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
请求发送至:
const express = require('express')
import { Request, Response } from "express"
import cors from 'cors'
const app = express()
app.use(cors({
credentials: true,
origin: "http://localhost",
allowedHeaders: [
'Content-Type',
'Authorization',
],
}));
const port = 2999
app.get('/', (req: Request, res: Response) => {
console.log(req.headers)
console.log(req.cookies)
res.send(true)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
您需要更多信息吗?
这里涉及两个不同的 HTTP 客户端:
您必须将传入请求中的 cookie 复制到传出(axios)请求中,也许是这样:
axios.get(url, {
headers: {cookie: req.headers.cookie}
})
在这种情况下,既不需要
withCredentials: true
也不需要 CORS 设置,因为仅当 HTTP 客户端是 浏览器时,两者才相关。
我知道这个问题已经得到了回答,但对于那些像我以前的自己一样偶然发现这个问题的人,我建议添加两件事:
app.use(cors({ credentials: true, origin: 'http://localhost:xxxx' }));
updateItem(id: string, updatedItem: ItemModel) {
// Update the item on the server
return this.http.put('http://localhost:xxxx/api/item/' + id, updatedItem,
{withCredentials: true}).pipe( //rest of code
还有我的饼干:
res.cookie('authToken', token, {
domain: 'localhost',
httpOnly: true,/* secure: true, if using HTTPS */
secure: false,
sameSite: sameSite,
path: '/',
maxAge: 3600000, /* 1 hour */
});
当我检查“网络”选项卡时,cookie 存在,但当我记录它时不存在:console.log(req.cookies) 它是“[Object: null prototype] {}”。我最近实现了这个,所以这也可能会消失,但目前它是有效的。