在NodeJs http请求中传递cookie

我在NodeJs中是一个新手。 我试图做一个HTTP请求,并通过一个cookie。 我已经读过关于它的所有线程stackoverflow,并构成了一段理论上应该工作的代码。 但是,它不。

我试图做的是发送一个cookie的商店代码到一个网上商店,这将告诉我关于这家商店的信息。 如果没有cookie,它会显示默认的div要求select一家商店。

这是我的代码:

 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); 

我认为cookie会被发送并被我的请求接受,但事实并非如此。 我也尝试过jar 。 我在代码中评论了它。 但是,似乎也不适合我。 当我做console.log(resp.headers)我看到原始的cookie,但不是我的。 有人可以给我一个提示吗?

Cookie结构是正确的。 当我运行document.cookie=cookie; 在谷歌C​​hrome控制台它succssssly取代。

在你的头文件中,尝试直接放入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' } 

不幸的是,两个答案都不适合我。 我将重复一遍,其目的是通过传递包含商店代码的cookie来发起http请求。 为了得到这个分支的页面HTML,而不是标准页面要求我select一个。 尝试这两个选项后,我没有得到任何错误,但也没有通过cookie的网站。 但是非常感谢Subject为我提供的function。 它给了我一个想法,使用JSDOM和提供的头。 所以这里是为我工作的代码:

 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()); } }); 

cookie被成功设置,我得到了我想要的这个分支的网页源代码。 谢谢你的答案,并希望它会帮助别人。

你的variablescookieString是一个Set-Cookie头。 这是服务器发送给客户端的服务器头,但不是客户端发送给服务器的cookie。

Set-Cookie标题:

  MC_STORE_ID=66860; expires=1234; 

客户端发送Cookie标头:

  MC_STORE_ID=66860; 

试试这些function:

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

开始使用这个:

 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返回一个对象。

那么你可以在你的头文件中设置它:

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

我有同样的问题,@Ricardo帮我弄清楚了。 我已经从头部删除了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)}); } }); 

这是您的Cookie数据和我的请求function之间的混合。