如何使用 cookie 创建 HTTP 客户端请求? [英] How do I create a HTTP Client Request with a cookie?
问题描述
我有一个 node.js Connect 服务器来检查请求的 cookie.要在节点中测试它,我需要一种方法来编写客户端请求并将 cookie 附加到它.我知道 HTTP 请求为此具有cookie"标头,但我不确定如何设置和发送——我还需要在同一个请求中发送 POST 数据,所以我目前正在使用 danwrong 的 restler 模块,但它似乎不允许我添加该标题.
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.
关于如何使用硬编码的 cookie 和 POST 数据向服务器发出请求有什么建议吗?
Any suggestions on how I can make a request to the server with both a hard-coded cookie and POST data?
推荐答案
此答案已弃用,请参阅@ankitjaininfo 的答案下文 寻求更现代的解决方案
This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution
以下是我认为您仅使用节点 http 库使用数据和 cookie 发出 POST 请求的方式.此示例是发布 JSON,如果您发布不同的数据,请相应地设置您的内容类型和内容长度.
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.
// 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
What you send in the Cookie
value 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 客户端请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!