Home > Software design >  Why I couldn't set cookies with Node.js express?
Why I couldn't set cookies with Node.js express?

Time:10-03

Here's my code:

const app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser());

app.post("/pinfo", (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, async function (err, fields) {

        var nhs_num = 1000000; // it should be a return value from another function using fields values as parameters

        res.cookie("nhsnum", nhs_num, {
            expires: new Date(Date.now()   1000 * 60 * 5),
            httpOnly: true
        }); // set a cookie expired in 5 minutes
        console.log(req.cookies.nhsnum);
    })
});

The code is in a Node.js server, and it gets form submission from the HTML client, then uses the form details to get a result and finally saves it into the cookie.

When I try to log the cookie, there is an undefined in the console. And I don't understand why. Is there any process that I did wrong? I really appreciate it if there is someone could help me figure this out.

CodePudding user response:

req.cookies contains the cookies that arrived with this incoming request. It does not contain the cookies that will be set on the response and sent back to the client.

So, when you do res.cookie(...) that is adding a cookie to the response object (technically adding a set-cookie header to the response) so the client will pick up that cookie when it gets the response.

If you want to see the cookie in req.cookies, then look at req.cookies on the next request from that client (before the cookie expires). Your newly created cookie should then show on that next request.

In this request, you can see the outgoing cookies by doing this:

console.log(res.getHeaders());

And, you will see your nhsnum cookie like this:

[Object: null prototype] {
  'x-powered-by': 'Express',
  'set-cookie': 'nhsnum=1; Path=/; Expires=Mon, 03 Oct 2022 00:08:01 GMT; HttpOnly'
}

CodePudding user response:

Is your client the same source as the server?if not,you should at client page setting request mode,credentials: "include",

  • Related