简单的NodeJS http请求相当于curl

我无法通过nodeJS将curl转换为等效的http请求。 我正在使用请求模块,但我似乎做错了请求时。 当我运行它,它给了我

body: Cannot POST /path 

不知道如何debugging这个,有什么想法?

 var data = JSON.stringify({ 'sender': { 'name': 'name', 'handle': 'handle' }, 'subject': 'Title here', 'body': 'something something', 'metadata': {} }); var options = { host: 'website.com', path: '/path', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer <token>', 'Accept': 'application/json', 'Content-Length': Buffer.byteLength(data) } }; var req = http.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { console.log("body: " + chunk); }); }); req.write(data); req.end(); 

下面是我试图为上述nodejs做的等效curl(那工作)。

 curl --include \ --request POST \ --header "Content-Type: application/json" \ --header "Authorization: Bearer <token>" \ --header "Accept: application/json" \ --data-binary "{ \"sender\": { \"name\": \"name\", \"handle\": \"handle\" }, \"subject\": \"Title here\", \"body\": \"something something\", \"metadata\": {} }" \ 'website.com/path" 

您可以使用json参数直接包含您的JSON数据与请求库:

 var request = require('request'); var options = { uri: 'http://website.com/path', method: 'POST', headers: { 'Authorization': 'Bearer <token>', 'Accept': 'application/json' }, json: { 'sender': { 'name': 'name', 'handle': 'handle' }, 'subject': 'Title here', 'body': 'something something', 'metadata': {} } }; var req = request(options, function(error, response, body) { if (error) { console.log(error); return; } if (response.statusCode == 200) { console.log(body); } else { console.log("receive status code : " + response.statusCode); } }); 

从请求选项doc :

json – 将body设置为值的JSON表示,并添加Content-type:application / json头。 此外,将响应正文parsing为JSON。