更新node.js中的post http请求长度
我正在使用node.js发布一个http请求。如果我在“选项”字段之前定义了我的post数据,那么代码可以使用,但是如果我最初将post_数据字符串设置为空,然后更新它,那么它不会选择新的长度。我怎样才能让它这么做?我期待着发送不同长度的多个帖子到一个循环中的同一个地方,所以需要能够做到这一点更新node.js中的post http请求长度,node.js,post,Node.js,Post,我正在使用node.js发布一个http请求。如果我在“选项”字段之前定义了我的post数据,那么代码可以使用,但是如果我最初将post_数据字符串设置为空,然后更新它,那么它不会选择新的长度。我怎样才能让它这么做?我期待着发送不同长度的多个帖子到一个循环中的同一个地方,所以需要能够做到这一点 var post_data=''; //if i set my string content here rather than later on it works var options = {
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();
您在设置post_data
之前运行了此操作
如果要在创建对象后设置post_data
,则需要稍后手动设置:
options.headers['Content-Length'] = post_data.length;
请注意,在调用http.request()之前,必须设置发布数据是发送一个查询字符串作为请求主体的问题(就像在请求之后发送URL一样) 这还需要声明内容类型和内容长度值,以便服务器知道如何解释数据
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();
您需要替换:
'Content-Length': post_data.length
用于:
请参见您的长度错误>您需要报告UTF8编码的字节数;不是Unicode码点数。请不要使用data.length,我突然提到了这个问题,作者说不要使用data.length,而是使用Buffer.bytellength(数据)。参考问题:和参考问题:嗯。。。因此,由于我在每篇文章中都使用'req.write',并且只调用'http.request'一次,所以我永远无法更改我访问的数据的大小post@user1305541:当然不是。HTTP头在有效负载之前发送;发送到服务器后无法更改标头。如果要查找字符串的内容长度,请始终使用Buffer.ByTellength()!当您想查找字符串的内容长度时,请始终使用Buffer.byteLength()!
'Content-Length': post_data.length
'Content-Length': Buffer.byteLength(post_data, 'utf-8')