我试图做使用下面的代码中的NodeJS一个HTTPS REST请求:创建的NodeJS HTTPS休息身体要求JSON
var querystring = require('querystring');
var https = require('https');
var postData = {
'Value1' : 'abc1',
'Value2' : 'abc2',
'Value3' : '3'
};
var postBody = querystring.stringify(postData);
var options = {
host: 'URL'
port: 443,
path: 'PATH'
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postBody.length
}
};
var req = https.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.write(postBody);
req.end();
req.on('error', function(e) {
console.error(e);
});
请求的作品,但并不如预期。该机构将在JSON格式不发,看起来像:
RequestBody":"Value1=abc1&Value2=abc2&Value3=3
输出应该看起来像:
RequestBody":"[\r\n {\r\n \"Value3\": \"3\",\r\n \"Value2\": \"abc2\",\r\n \"Value1\": \"abc1\"\r\n }\r\n]
我认为这是与字符串化,也许我将它转化以JSON格式无论如何..
这并没有改变输出,反正谢谢。 –
我刚刚意识到您将数据作为字符串传递。这不是必需的,你可以传递一个Object。 – Eliasib13
如果我通过删除stringify命令来尝试这样做,我会得到以下错误:TypeError:第一个参数必须是字符串或缓冲区 –