gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:54:11 27 4
gpt4 key购买 nike

我有一个 node.js Connect 服务器来检查请求的 cookie。要在 Node 中测试它,我需要一种方法来编写客户端请求并将 cookie 附加到它。我知道 HTTP 请求为此具有“cookie” header ,但我不确定如何设置和发送——我还需要在同一个请求中发送 POST 数据,所以我目前正在使用 danwrong 的 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

关于http-headers - 如何使用 cookie 创建 HTTP 客户端请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4579757/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com