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

Van*_*ril 45 http-headers node.js

我有一个node.js Connect服务器来检查请求的cookie.要在节点内测试它,我需要一种方法来编写客户端请求并附加cookie.我知道HTTP请求有'cookie'标题,但我不知道如何设置它并发送 - 我还需要在同一个请求中发送POST数据,所以我目前正在使用danwrong的restler模块,但它似乎没有让我添加标题.

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

Ran*_*Etc 51

这个答案已被弃用,请参阅下面的 @ ankitjaininfo的答案以获得更现代的解决方案


以下是我认为您仅使用节点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();
Run Code Online (Sandbox Code Playgroud)

您在Cookie值中发送的内容应该取决于您从服务器收到的内容.维基百科对这些内容的撰写非常好:http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

  • 现在不推荐使用`http.createClient`.请参考我的新答案. (2认同)

ank*_*nfo 38

使用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();
Run Code Online (Sandbox Code Playgroud)