【问题标题】:Updating post http request length in node.js更新 node.js 中的 post http 请求长度
【发布时间】:2014-10-14 20:19:45
【问题描述】:

我正在使用 node.js 发布一个 http 请求。如果我在“选项”字段之前定义我的帖子数据,则该代码适用,但如果我最初将我的 post_data 字符串设置为空并稍后更新它,它不会获取新的长度。我将如何让它做到这一点?我希望将多个不同长度的帖子循环发送到同一个地方,因此需要能够做到这一点。

var post_data=''; //if i set my string content here rather than later on it works

var options = {
        host: '127.0.0.1',
        port: 8529,
        path: '/_api/cursor',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': post_data.length
        }
    };

    var req = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });

    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });

   post_data = 'a variable length string goes here';//the change in length to post_data is not                     //recognised    
   req.write(post_data);
   req.end();        

【问题讨论】:

标签: node.js post


【解决方案1】:
'Content-Length': post_data.length

你在设置 post_data 之前运行了这个。

如果要在创建对象后设置post_data,则需要稍后手动设置:

options.headers['Content-Length'] = post_data.length;

请注意,您必须在调用 http.request() 之前进行设置。

【讨论】:

  • mmm...所以我对每个帖子都使用'req.write'并且只调用一次'http.request',我永远无法更改我发布的数据的大小
  • @user1305541:当然不是。 HTTP 标头在有效负载之前发送;将标头发送到服务器后,您无法更改标头。
  • 当你想查找字符串的内容长度时,总是使用 Buffer.byteLength() ! github.com/visionmedia/express/issues/1749
【解决方案2】:

发布数据是发送一个查询字符串(就像您在 ? 之后使用 URL 发送它的方式一样)作为请求正文。

这还需要声明 Content-Type 和 Content-Length 值,以便服务器知道如何解释数据。

var querystring = require('querystring');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': data.length
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

【讨论】:

【解决方案3】:

你需要更换:

'Content-Length': post_data.length

为:

'Content-Length': Buffer.byteLength(post_data, 'utf-8')

https://github.com/strongloop/express/issues/1870

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 2021-08-18
    • 2020-07-10
    • 2023-03-05
    • 1970-01-01
    • 2014-07-01
    相关资源
    最近更新 更多