javascript - Cookie is not included in request headerServer side cannot read req.cookies - Stack Overflow

I am learning and applying authentication for my blog website!I am using express-session to handle log

I am learning and applying authentication for my blog website!

I am using express-session to handle logins. Cookie on the browser & server sessions works fine.

However, I am having trouble retrieving cookies on the server-side express app. I tried the following:

  • With cookie-parser, req.cookies & req.signedCookies both returns [Object: null prototype].
  • Setting CORS
  • req.cookie & req.header.cookie returns undefined
  • I can see a "Cookie" header from my connection in the browser network tab.

My code / settings are as follows:

function auth (req, res, next) {
  // Problem: Cannot read browser cookie of HTTP requests.
  console.log('Based on browser', req.cookie, req.cookies, req.signedCookies);
  next();
}

router.get('/', auth, async (req, res) => { // ... }

Middlewares

app.use(cors({
  origin: ['http://localhost:3000'],
  credentials: true
}));
app.use(cookieParser())  // Also tried with secret option.
app.use(session({
  secret: 'top-secret',
  resave: true,
  rolling: true,
  saveUninitialized: false,
  store: store, // this is working
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 14,
    httpOnly: true,
    secure: process.env.NODE_ENV !== 'Development',
    sameSite: process.env.NODE_ENV === 'Development' ? 'lax' : 'none'
  }
}))

Thank you in advance :)

Edit 1: My fetch code:

I am learning and applying authentication for my blog website!

I am using express-session to handle logins. Cookie on the browser & server sessions works fine.

However, I am having trouble retrieving cookies on the server-side express app. I tried the following:

  • With cookie-parser, req.cookies & req.signedCookies both returns [Object: null prototype].
  • Setting CORS
  • req.cookie & req.header.cookie returns undefined
  • I can see a "Cookie" header from my connection in the browser network tab.

My code / settings are as follows:

function auth (req, res, next) {
  // Problem: Cannot read browser cookie of HTTP requests.
  console.log('Based on browser', req.cookie, req.cookies, req.signedCookies);
  next();
}

router.get('/', auth, async (req, res) => { // ... }

Middlewares

app.use(cors({
  origin: ['http://localhost:3000'],
  credentials: true
}));
app.use(cookieParser())  // Also tried with secret option.
app.use(session({
  secret: 'top-secret',
  resave: true,
  rolling: true,
  saveUninitialized: false,
  store: store, // this is working
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 14,
    httpOnly: true,
    secure: process.env.NODE_ENV !== 'Development',
    sameSite: process.env.NODE_ENV === 'Development' ? 'lax' : 'none'
  }
}))

Thank you in advance :)

Edit 1: My fetch code:

Share Improve this question edited Dec 30, 2021 at 9:04 Dave Yu asked Dec 30, 2021 at 8:41 Dave YuDave Yu 4121 gold badge6 silver badges18 bronze badges 7
  • Are you making ajax requests? Because those don't transmit cookies by default. (edit: cross-origin ones) – user5734311 Commented Dec 30, 2021 at 8:47
  • Hello Chris, I made request with the fetch API – Dave Yu Commented Dec 30, 2021 at 8:48
  • 1 Yes, but from a different server I assume? That means you need to enable the transmission of cookies by adding credentials: include to the fetch options. developer.mozilla/en-US/docs/Web/API/fetch#syntax – user5734311 Commented Dec 30, 2021 at 8:51
  • I didn't include that option before. But adding that option unfortunately did not solve the issue. :( – Dave Yu Commented Dec 30, 2021 at 9:00
  • Can you show relevant fetch code? – user5734311 Commented Dec 30, 2021 at 9:00
 |  Show 2 more ments

2 Answers 2

Reset to default 3

If your using http only you should consider 2 things:

Step1 while request in client side: you should send request like this:

        const req = await fetch("http://localhost:7000/api/auth/login", {
      method: "POST",
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Credentials": true,
      },
      body: JSON.stringify({
        email: formData.get("email"),
        password: formData.get("password"),
      }),
    });
    const data = await req.json();

step 2 in express:

const allowedOrigins = ["http://localhost:8000"];
    const corsOptions = {
    origin: function (origin, callback) {
   if (allowedOrigins.indexOf(origin) !== -1) {
  callback(null, true);
    } else {
     var msg =
    "The CORS policy for this site does not " +
    "allow access from the specified Origin.";
     callback(new Error(msg), false);
   }
 },
optionsSuccessStatus: 200,
 credentials: true,
 };
app.use(cors(corsOptions));

now you can get coockies in express by using req.cookies.nameOfCookiesWhichYouSendThroughCoockieParser

I'm using axios (React) + Express-js on Node-js

On the client side- In order to get the cookie from the server:
Simply set withCredentials: true in the axios request, you can use this config example:

const config = {
  headers: {
    "Content-Type": "application/json",
  },
  withCredentials: true,
};

On the server side- In order to get the cookie from the client:
You also need to set withCredentials: true in the axios request,
And you need to install cookie-parser library on the server:

npm i cookie-parser

Import this library:

const cookieParser = require("cookie-parser");

And use the cookieParser middleware:

app.use(cookieParser());

And finally, req.cookies should return the list of your cookies.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745088078a4610525.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信