Node.js 如何从节点服务器发送http post调用?
我试图在Node.js 如何从节点服务器发送http post调用?,node.js,post,Node.js,Post,我试图在https://api-mean.herokuapp.com/api/contacts包含以下数据: { "name": "Test", "email": "test@xxxx.in", "phone": "989898xxxx" } 但没有得到任何回应。 我也和邮递员试过,效果很好。我收到了邮递员的回信 我正在使用以下nodejs代码: var postData = querystring.stringify({ "na
https://api-mean.herokuapp.com/api/contacts
包含以下数据:
{
"name": "Test",
"email": "test@xxxx.in",
"phone": "989898xxxx"
}
但没有得到任何回应。
我也和邮递员试过,效果很好。我收到了邮递员的回信
我正在使用以下nodejs代码:
var postData = querystring.stringify({
"name": "Test",
"email": "test@xxxx.in",
"phone": "989898xxxx"
});
var options = {
hostname: 'https://api-mean.herokuapp.com',
path: '/api/contacts',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
var req = http.request(options, function (res) {
var output = '';
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', function () {
var obj = JSON.parse(output.trim());
console.log('working = ', obj);
resolve(obj);
});
});
req.on('error', function (e) {
console.error(e);
});
req.write(postData);
req.end();
我少了什么吗
如何从节点服务器发送http post调用?要从节点服务器发送http-post调用,您可能需要使用 样本:
var request = require('request');
request({
url: "some site",
method: "POST",
headers: {
// header info - in case of authentication enabled
},
json:{
// body goes here
}, function(err, res, body){
if(!err){
// do your thing
}else{
// handle error
}
});
我建议您使用该模块使事情变得更简单
var request=require('request');
var json = {
"name": "Test",
"email": "test@xxxx.in",
"phone": "989898xxxx"
};
var options = {
url: 'https://api-mean.herokuapp.com/api/contacts',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: json
};
request(options, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
console.log(body);
}
});
谢谢你的回复。正在工作但正在获取错误:[错误:无效协议:null]存在一些代理问题来设置npm配置代理是一些API返回
200
,201
以获得成功结果