node.js 如何使用 cookie 创建 HTTP 客户端请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4579757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:47:18  来源:igfitidea点击:

How do I create a HTTP Client Request with a cookie?

http-headersnode.js

提问by Vanwaril

I've got a node.js Connect server that checks the request's cookies. To test it within node, I need a way to write a client request and attach a cookie to it. I understand that HTTP Requests have the 'cookie' header for this, but I'm not sure how to set it and send -- I also need to send POST data in the same request, so I'm currently using danwrong's restler module, but it doesn't seem to let me add that header.

我有一个 node.js Connect 服务器来检查请求的 cookie。为了在 node 中测试它,我需要一种方法来编写客户端请求并将 cookie 附加到它。我知道 HTTP 请求具有用于此的“cookie”标头,但我不确定如何设置和发送——我还需要在同一个请求中发送 POST 数据,所以我目前正在使用 danwrong 的 restler 模块,但它似乎不允许我添加该标题。

Any suggestions on how I can make a request to the server with both a hard-coded cookie and POST data?

关于如何使用硬编码 cookie 和 POST 数据向服务器发出请求的任何建议?

回答by RandomEtc

This answer is deprecated, please see @ankitjaininfo's answer belowfor a more modern solution

此答案已弃用,请参阅下面@ankitjaininfo 的答案以获取更现代的解决方案



Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

这是我认为您仅使用节点 http 库使用数据和 cookie 发出 POST 请求的方式。此示例发布 JSON,如果您发布不同的数据,请相应地设置您的内容类型和内容长度。

// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request

var http = require('http');

var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'

var client = http.createClient(80, 'www.example.com');

var headers = {
    'Host': 'www.example.com',
    'Cookie': cookie,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data,'utf8')
};

var request = client.request('POST', '/', headers);

// listening to the response is optional, I suppose
request.on('response', function(response) {
  response.on('data', function(chunk) {
    // do what you do
  });
  response.on('end', function() {
    // do what you do
  });
});
// you'd also want to listen for errors in production

request.write(data);

request.end();

What you send in the Cookievalue should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

您发送的Cookie值应该真正取决于您从服务器收到的内容。维基百科对这些东西的描述非常好:http: //en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

回答by ankitjaininfo

The use of http.createClientis now deprecated. You can pass Headers in options collection as below.

采用http.createClient现在已经过时。您可以在选项集合中传递标题,如下所示。

var options = { 
    hostname: 'example.com',
    path: '/somePath.php',
    method: 'GET',
    headers: {'Cookie': 'myCookie=myvalue'}
};
var results = ''; 
var req = http.request(options, function(res) {
    res.on('data', function (chunk) {
        results = results + chunk;
        //TODO
    }); 
    res.on('end', function () {
        //TODO
    }); 
});

req.on('error', function(e) {
        //TODO
});

req.end();

回答by ranm8

You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.

你可以使用Requestify来做到这一点,它是我为 nodeJS 编写的一个非常简单和酷的 HTTP 客户端,它支持轻松使用 cookie,还支持缓存。

To perform a request with a cookie attached just do the following:

要执行附加 cookie 的请求,只需执行以下操作:

var requestify = require('requestify');
requestify.post('http://google.com', {}, {
    cookies: {
        sessionCookie: 'session-cookie-data'   
    }
});