3

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);
Nayana Shekar C
  • 111
  • 2
  • 6

2 Answers2

0

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']

darkbasic
  • 169
  • 2
  • 11
0

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.

Nivesh
  • 2,573
  • 1
  • 20
  • 28