2017-09-25 148 views
0

我试图做使用下面的代码中的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格式无论如何..

回答

0

在请求的标题中指定'Content-Type': 'application/x-www-form-urlencoded'。您可以尝试将其更改为'Content-Type': 'application/json'

+0

这并没有改变输出,反正谢谢。 –

+0

我刚刚意识到您将数据作为字符串传递。这不是必需的,你可以传递一个Object。 – Eliasib13

+0

如果我通过删除stringify命令来尝试这样做,我会得到以下错误:TypeError:第一个参数必须是字符串或缓冲区 –

0

您需要更改内容type.try这样

var querystring = require('querystring'); 
var https = require('https'); 

var postData = { 
    'Value1' : 'abc1', 
    'Value2' : 'abc2', 
    'Value3' : '3' 
}; 
var postBody = postData; 

var options = { 
    host: 'URL' 
    port: 443, 
    path: 'PATH' 
    method: 'POST', 
    headers: { 
     'Content-Type': 'application/json', 

    } 
}; 

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); 
}); 
+0

与上面相同的错误:TypeError:第一个参数必须是字符串或Buffer –

0

我解决我的问题有以下几点。

jsonObject = JSON.stringify({ 
    'Value1' : 'abc1', 
    'Value2' : 'abc2', 
    'Value3' : '3' 
}); 
var postheaders = { 
    'Content-Type' : 'application/json', 
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8') 
};