用axios请求传递cookie



我试图通过axios请求传递cookie(这是在浏览器中设置的(例如Edge V102.0.1245.44或Firefox V89.0.2))到另一个服务器(在同一主机上= localhost)。我仍然尝试了很多不同的设置,但都不奏效。cookie似乎存在于express request (http://localhost:3000/request)req.headers.cookie.

:

使Axios在请求中自动发送cookie

node.js axios request with cookies

为跨域请求设置cookie

在节点中发送请求时如何设置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客户端:

  • http://localhost:3000/setcookie请求是由您的浏览器发出的,并且浏览器存储该cookie。
  • http://localhost:2999请求是由Node.js进程发出的,它对浏览器的cookie一无所知。

您必须将传入请求中的cookie复制到传出(axios)请求中,可能是这样的:

axios.get(url, {
headers: {cookie: req.headers.cookie}
})

在这种情况下,既不需要withCredentials: true也不需要CORS设置,因为只有当HTTP客户端是浏览器时,它们才相关。

相关内容

  • 没有找到相关文章

最新更新