在NodeJs http请求中传递Cookie

编程入门 行业动态 更新时间:2024-10-25 01:20:55
本文介绍了在NodeJs http请求中传递Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是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

本文发布于:2023-11-26 08:04:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NodeJs   http   Cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!