Unable to set cookie in browser using request and express modules in NodeJS

I am having a client and a server node written in express. The client communicates with server using request module, the server will send response back to the client. Here in server code I am sending cookie back to the client. But I am unable to see the cookies in the browser. In client req.cookies is giving {}

Server code:

var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.get('/test-cookie', function(req, res) {
    res.cookie('abc', 'xyz').send('Cookie is set');
});
app.listen(9000);

Client code:

var express = require('express');
var request = require('request');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.get('/', function(req, res) {
    request({
        url: 'http://localhost:9000/test-cookie',
        method: 'GET'
    }, function(error, response, body) {
        if (error) {
            res.send({
                msg: error
            });
        } else {
            if (200 == response.statusCode) {
                console.log(req.cookies);
            }
        }
    });
});
app.listen(7000);

Answers


Client browser for first hit to 7000 api will not contain any cookie, thus req.cookies will log {}, thus we have to set cookie in the res for the client browser to send the cookie for the rest requests.

Solution (Client Code):

if (200 == response.statusCode) {

    // For first request it will be empty {}
    console.log(req.cookies);

    /* fetching the cookie from the response header
     * and setting in res to be set in the browser
     */
    var c = response.headers['set-cookie'];
    res.set('set-cookie',c[0]);

    res.send('Done');

}

Explanation: What you are doing is trying to fetch cookies from req which does not contain any cookie. The response object you are getting from hitting the 9000 api will contain the cookie. Thus, you have to set the cookie from response to the res for client browser.


response.cookies is to SET cookies, if you want to GET cookies from a response object you will have to rely on response.headers['set-cookie']


Need Your Help

Creating an Object and initialize it with passing parameters in Java

java object parameters

I am trying to create a new object and initialize it with the parameters which are passed by the following command :

add link to list of post terms

php wordpress function categories

I need to change the function below so that it outputs a list if links rather than a string. So the resulting html i need is <a href="#">term</a>.