Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing cookies in NodeJs http request

I'm kind of a newbie in NodeJs. I'm trying to make an http request and pass a cookie. I've read all the threads on stackoverflow about it and made up a piece of code that should theoretically work. But, it doesn't.

What I'm trying to do is to send a cookie with the store code to one online-shop which will show me the information about this very shop. If there is no cookie it shows the default div asking to choose a shop.

Here is my code:

var request = require('request'),     http = require('follow-redirects').http,     request = request.defaults({         jar: true     });  var cookieString = 'MC_STORE_ID=66860; expires=' + new Date(new Date().getTime() + 86409000); var str = ''; //var uri = 'example.de';  //var j = request.jar(); var cookie = request.cookie(cookieString); j.setCookie(cookie, uri);  var options = {     hostname: 'example.de',     path: '/pathexample',     method: 'GET',     headers: {         'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',             'Cookie': cookie,             'Accept': '/',             'Connection': 'keep-alive'     }     //,jar: j };  http.request(options, function (resp) {     resp.setEncoding('utf8');     console.log(resp.headers);     if (resp.statusCode) {         resp.on('data', function (part) {             str += part;         });         resp.on('end', function (part) {             console.log(str);         });          resp.on('error', function (e) {             console.log('Problem with request: ' + e.message);         });     } }).end(str); 

I assume that the cookie will be sent and accepted with my request, but it isn't. I've also tried jar. I commented it out in the code. But, it seems not to work for me either. When I do console.log(resp.headers) I see the original cookies, but not mine. Can someone give me a hint?

The cookie structure is correct. When I run document.cookie=cookie; in google chrome console it is succsessfuly replaced.

like image 352
Jevgeni Jostin Avatar asked Jun 23 '14 12:06

Jevgeni Jostin


People also ask

Can we set cookie in post request?

Creating cookies. After receiving an HTTP request, a server can send one or more Set-Cookie headers with the response. The browser usually stores the cookie and sends it with requests made to the same server inside a Cookie HTTP header.

How do I request a cookie in node js?

createServer(function (request, response) { // To Read a Cookie const cookies = parseCookies(request); // To Write a Cookie response. writeHead(200, { "Set-Cookie": `mycookie=test`, "Content-Type": `text/plain` }); response. end(`Hello World\n`); }). listen(8124); const {address, port} = server.

How do I pass cookies in HTTP request?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

How do I use cookie parser in node js?

Now to use cookies with Express, we will require the cookie-parser. cookie-parser is a middleware which parses cookies attached to the client request object. To use it, we will require it in our index. js file; this can be used the same way as we use other middleware.


2 Answers

In your headers try to put directly the cookieString

headers: {     'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',     'Cookie': cookieString,     'Accept': '/',     'Connection': 'keep-alive' } 
like image 60
Riccardo Avatar answered Sep 20 '22 14:09

Riccardo


I had the same issue, @Ricardo helped me to figure out. I have removed the jar key from header

//Set the cookie instead of setting into header var cookie = request.cookie('MC_STORE_ID=66860');   // Set the headers for the request var headers = {     'Content-Type': 'application/json',     'Content-Length': Buffer.byteLength(post_data),     'Cookie': cookie }; // Configure the request var options = {     url: requestObj["URL"],     method: 'POST',     headers: headers };  // Start the request request(options, function (error, response, body) {     if (!error && response.statusCode === 200) {         // Print out the response body         cb(null, {status: 0, statusDsc: "success", data: body});     } else {         cb(error, {status: 2, statusDsc: JSON.stringify(error)});     } }); 

This is kind of mix between your cookie data and my request function.

like image 24
Pini Cheyni Avatar answered Sep 18 '22 14:09

Pini Cheyni