Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
241 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...