Question

I am calling an http post request(login request from another 3rd party server) from node and want to save the cookie for future http requests.

var options = {
    host: 'hostname.com',
    port: '80',
    path: '/login.php',
    method: 'POST'
};

var data = qs.stringify({
    uname: "validUsername",
    password: "validPassword"
});

var req = http.request(options, function(response) {
    console.log(response.statusCode);
    console.log('HEADERS: ' + JSON.stringify(response.headers));

    // console.log('Cookies: ' + response.getHeader("Set-Cookie"));
    response.setEncoding('utf8');

    response.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
    });
});

req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

req.write(data);
req.end();

How can i access and save the cookie from the response sent by the requested server?

Was it helpful?

Solution

You should be able to get the header with response.headers['set-cookie'];.

If you need to actually parse them, you could use a module like cookie (what Express uses) or cookiejar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top