[英]node.js + post request
I am trying to call post data method of another application(which is running in localhost:3000) using node.js. 我正在尝试使用node.js调用另一个应用程序(正在localhost:3000中运行)的发布数据方法。 But its returning error..
但是它的返回错误。
The following is the code: 以下是代码:
var options = {
host: 'localhost',
path: '/v1/key/11111111',
//since we are listening on a custom port, we need to specify it by hand
port: '3000',
//This is what changes the request to a POST request
method: 'POST',
headers: {'Content-Type': 'application/json'}
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("hello world!");
req.end();
But i am receiving error: 但我收到错误:
{"meta":{"version":1,"status_code":400},"results":{"error":{"type":"Error","message":"invalid json"}}}
When i am trying using CURL
command i am getting the desired result: 当我尝试使用
CURL
命令时,我得到了预期的结果:
curl -X POST localhost:3000/v1/key/12345678 --header "Content-Type:application/json"
My question is how i have to construct POST request for the above requirement
. 我的问题是我必须如何
POST request for the above requirement
构建POST request for the above requirement
。
You specify 'application/json' in the request options. 您可以在请求选项中指定“ application / json”。 But you provide the string "Hello world!", which is not json, and that's what the error message tells you.
但是,您提供的字符串“ Hello world!”不是json,这就是错误消息告诉您的内容。
Try changing the header or the content. 尝试更改标题或内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.