Home > database >  Pass cookie with axios request
Pass cookie with axios request

Time:07-16

I'm trying to pass a cookie (which was set in the browser (e. g. Edge V102.0.1245.44 or Firefox V89.0.2)) by an axios request to another server (which is on the same host = localhost). I still tried a lot of different settings, but none did work. The cookie seems to be existing in the express request (http://localhost:3000/request) req.headers.cookie.

See:

Make Axios send cookies in its requests automatically

node.js axios request with cookies

Set cookies for cross origin requests

How to set cookies when send a request in node ?

Here is an example what I tried:

Send request http://localhost:3000/request, cookie is set before by 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}`)
})

Request is send to:

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}`)
})

Do you need more information?

CodePudding user response:

There are two different HTTP clients involved here:

  • The http://localhost:3000/setcookie request is made by your browser and the browser stores the cookie.
  • The http://localhost:2999 request is made by your Node.js process, which knows nothing about the browser's cookies.

You would have to copy the cookies from the incoming request into the outgoing (axios) request, perhaps so:

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

Neither withCredentials: true nor CORS settings are needed in this case, because both are relevant only if the HTTP client is a browser.

  • Related