我有一个 node .判断请求cookie的js Connect服务器.为了在 node 中测试它,我需要一种方法来编写客户端请求并向其附加cookie.我知道HTTP请求有这个"cookie"头,但我不确定如何设置和发送——我还需要在同一个请求中发送POST数据,所以我目前正在使用DanError的restler模块,但它似乎不允许我添加这个头.
关于如何使用硬编码cookie和POST数据向服务器发出请求,有什么建议吗?
我有一个 node .判断请求cookie的js Connect服务器.为了在 node 中测试它,我需要一种方法来编写客户端请求并向其附加cookie.我知道HTTP请求有这个"cookie"头,但我不确定如何设置和发送——我还需要在同一个请求中发送POST数据,所以我目前正在使用DanError的restler模块,但它似乎不允许我添加这个头.
关于如何使用硬编码cookie和POST数据向服务器发出请求,有什么建议吗?
此答案已被弃用,请参阅@ankitjaininfo的答案below以了解更现代的解决方案
我认为您可以使用 node 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();
Cookie
值中发送的内容实际上应该取决于从服务器接收到的内容.维基百科对这些东西的描述相当不错:http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes