Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...