简体   繁体   English

在NodeJs http请求中传递cookie

[英]Passing cookies in NodeJs http request

I'm kind of a newbie in NodeJs. 我是NodeJs的新手。 I'm trying to make an http request and pass a cookie. 我正在尝试发出http请求并传递cookie。 I've read all the threads on stackoverflow about it and made up a piece of code that should theoretically work. 我已经阅读了有关它的stackoverflow上的所有线程,并编写了一段理论上应该工作的代码。 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. 我想要做的是将带有商店代码的cookie发送到一个在线商店,它将向我显示有关这个商店的信息。 If there is no cookie it shows the default div asking to choose a shop. 如果没有cookie,它会显示要求选择商店的默认div

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. 我假设我的请求会发送和接受cookie,但事实并非如此。 I've also tried jar . 我也试过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. 当我做console.log(resp.headers)我看到原始的cookie,但不是我的。 Can someone give me a hint? 有人能给我一个暗示吗?

The cookie structure is correct. cookie结构是正确的。 When I run document.cookie=cookie; 当我运行document.cookie=cookie; in google chrome console it is succsessfuly replaced. 在谷歌C​​hrome控制台,它是succsessfuly替换。

In your headers try to put directly the cookieString 在你的标题中尝试直接放入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'
}

I had the same issue, @Ricardo helped me to figure out. 我有同样的问题,@ Ricardo帮助我搞清楚。 I have removed the jar key from header 我从标题中删除了jar密钥

//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. 这是您的cookie数据和我的请求函数之间的混合。

Unfortunately both answers didn't work for me. 不幸的是,这两个答案对我都不起作用。 I will repeat that the aim was to make a http request with passing a cookie containing the store code. 我将重复一遍,目的是通过传递包含商店代码的cookie来发出http请求。 To get the pages HTML for this very branch, not the standars page asking me to pick one. 要获取此分支的页面HTML,而不是要求我选择一个的标准页面。 After trying both options I didn't get any error, but also it didn't pass the cookie to the website. 尝试了两个选项后,我没有收到任何错误,但它也没有将cookie传递给网站。 But thanks a lot to Subject for providing me the functions. 但非常感谢Subject为我提供的功能。 It gave me an idea to use those and the offered header with a JSDOM. 它给了我一个想法,使用这些和提供的标头与JSDOM。 So here is the code which worked for me: 所以这里的代码对我有用:

var jsdom = require('jsdom');

var stores = ["68357"];

function dataCookieToString(dataCookie) {
    var t = "";
    for (var x = 0; x < dataCookie.length; x++) {
        t += ((t !== "") ? "; " : "") + dataCookie[x].key + "=" + dataCookie[x].value;
    }
    return t;
}

function mkdataCookie(cookie) {
    var t, j;
    cookie = cookie.toString().replace(/,([^ ])/g, ",[12],$1").split(",[12],");
    for (var x = 0; x < cookie.length; x++) {
        cookie[x] = cookie[x].split("; ");
        j = cookie[x][0].split("=");
        t = {
            key: j[0],
            value: j[1]
        };
        for (var i = 1; i < cookie[x].length; i++) {
            j = cookie[x][i].split("=");
            t[j[0]] = j[1];
        }
        cookie[x] = t;
    }
    return cookie;
}

var dataCookie = mkdataCookie('MC_STORE_ID=' + stores[0] + '; Expires=' + new Date(new Date().getTime() + 86409000));

jsdom.env({
    url: 'http://www.example.de',
    headers: {
        'User-Agent': "NodeJS/1.0",
            'Cookie': dataCookieToString(dataCookie)
    },
    scripts: ['http://code.jquery.com/jquery-1.5.min.js'],
    done: function (err, window) {
        var $ = window.jQuery;
        console.log($('body').html());
    }
});

The cookie was set succsessfuly and I got the webpages source code for this very branch I wanted. 这个cookie设置为succsessfuly,我得到了我想要的这个分支的网页源代码。 Thank you for the answers and hope it would help someone else. 谢谢你的答案,并希望它能帮助别人。

Your variable cookieString is a Set-Cookie header. 您的变量cookieString是一个Set-Cookie标头。 It's a server header that the server sends to the client but not a cookie that the client sends to the server. 它是服务器发送给客户端的服务器头,但不是客户端发送给服务器的cookie。

Set-Cookie header : Set-Cookie标头:

 MC_STORE_ID=66860; expires=1234;

The client sends in Cookie Header this: 客户端发送Cookie Header:

 MC_STORE_ID=66860;

Try these functions : 试试这些功能:

function dataCookieToString(dataCookie) {
    var t = "";
    for (var x = 0; x < dataCookie.length; x++) {
        t += ((t != "") ? "; " : "") + dataCookie[x].key + "=" + dataCookie[x].value;
    }
    return t;
}

function mkdataCookie(cookie) {
    var t, j;
    cookie = cookie.toString().replace(/,([^ ])/g, ",[12],$1").split(",[12],");
    for (var x = 0; x < cookie.length; x++) {
        cookie[x] = cookie[x].split("; ");
        j = cookie[x][0].split("=");
        t = {
            key: j[0],
            value: j[1]
        };
        for (var i = 1; i < cookie[x].length; i++) {
            j = cookie[x][i].split("=");
            t[j[0]] = j[1];
        }
        cookie[x] = t;
    }

    return cookie;
}

To start use this : 要开始使用此:

dataCookie = mkdataCookie('MC_STORE_ID=66860; expires=' + new Date(new Date().getTime() + 86409000));
// or mkdataCookie(resp.headers["set-cookie"]) in your `http.request.end()` function.

mkdataCookie returns an object. mkdataCookie返回一个对象。

Then you can set it in your header: 然后你可以在标题中设置它:

headers: {
    "User-Agent": "NodeJS/1.0",
    "Cookie": dataCookieToString(dataCookie)
}

To convert from array of cookies (coming from set-cookie header from response) to a request cookie: 要从Cookie数组(来自响应的set-cookie标头)转换为请求cookie:

    headers: {
     'cookie':cookies.map(c=>c.substr(0, c.indexOf(";"))).reduce((a, b) => a + "; " + b)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM