如何使用cookie创建HTTP客户端请求? [英] How do I create a HTTP Client Request with a cookie?

查看:618
本文介绍了如何使用cookie创建HTTP客户端请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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?

推荐答案

以下是我认为你只使用节点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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆