通过axios请求传递cookie

问题描述 投票:0回答:2

我试图通过 axios 请求将 cookie(在浏览器中设置(例如 Edge V102.0.1245.44 或 Firefox V89.0.2))传递到另一台服务器(位于同一主机 = localhost)。我仍然尝试了很多不同的设置,但没有一个起作用。 该cookie似乎存在于快速请求中(

http://localhost:3000/request
)
req.headers.cookie

参见:

让 Axios 自动在请求中发送 cookie

node.js axios 请求与 cookies

为跨源请求设置cookie

在node中发送请求时如何设置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}`)
})

您需要更多信息吗?

javascript node.js express cookies axios
2个回答
5
投票

这里涉及两个不同的 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 客户端是 浏览器时,两者才相关。


0
投票

我知道这个问题已经得到了回答,但对于那些像我以前的自己一样偶然发现这个问题的人,我建议添加两件事:

  1. 带有凭证和来源的cors实现:
app.use(cors({ credentials: true, origin: 'http://localhost:xxxx' }));
  1. withCredentials 到每个涉及 cookie 的请求(至少这对我有用)。这是我的客户端,在另一端(服务器)我使用中间件来检查 cookie 中的 JWT 令牌:
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] {}”。我最近实现了这个,所以这也可能会消失,但目前它是有效的。

© www.soinside.com 2019 - 2024. All rights reserved.