在NodeJs http请求中传递Cookie [英] Passing cookies in NodeJs http request
问题描述
我是NodeJs的新手。我试图发出http请求并传递一个cookie。我已经阅读了stackoverflow上的所有线程,并构成了一段代码,理论上应该工作。但是它不会。
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.
我想做的是将一个带有商店代码的cookie发送到一个在线商店,这将显示我的信息这个店。如果没有cookie,它显示默认 div
要求选择商店。
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.
这里是我的代码: / p>
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);
我假设cookie将被发送并接受我的请求,但不是。我也尝试过 jar
。我在代码中评论了它。但是,它似乎也不为我工作。当我做 console.log(resp.headers)
我看到原始的cookie,但不是我的。有人可以给我一个提示吗?
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?
Cookie结构正确。当我在Google Chrome控制台中运行 document.cookie = cookie;
时,它会成功替换。
The cookie structure is correct. When I run document.cookie=cookie;
in google chrome console it is succsessfuly replaced.
推荐答案
在标题中尝试直接放置cookieString
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'
}
这篇关于在NodeJs http请求中传递Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!