![](/img/trans.png)
[英]POST http://localhost:3000/data 400 (Bad Request) when trying to send data from client to server
[英]Trying to post data with Request NPM from NodeJS to localhost (Loopback Swagger API)
当我尝试使用此代码从nodejs发布实例回送时,我没有收到任何错误,但我也没有发布任何数据?
//NPM Package (request)
var request = require('request');
// Address of Loopback API on the same server
var api = "http://localhost:3000/api/devices";
//JSON Construction
var deviceInstance = {
"manufacturer": "manufacturer",
"model": "model"
//etc
}
// NPM (request)
request({
url: api,
method: "POST",
headers: {"Accept: application/json"},
json: true,
body: deviceInstance
}, function (error, response, body) {
if(error) {
console.log('error: '+ error);
} else {
console.log('document saved to api')
console.log(body);
console.log(response);
}
});
process.exit();
我没有从同一台机器的服务器得到任何响应或错误。 如果我在邮递员(Windows应用程序)中尝试相同的调用,它实际上在API中创建了一个实例,那么为什么我的本地节点不能连接到API?
为什么要process.exit() ?
调用process.exit()将强制进程尽快退出,即使仍有异步操作挂起。
您看到的行为是因为Javascript的异步性质。
您的代码从上到下启动 POST请求,然后在请求完成之前调用process.exit()
,从而提供您所看到的行为并“中断”您的代码。
从那里你有两个解决方案:
//NPM Package (request)
var request = require('request');
// Address of Loopback API on the same server
var api = "http://localhost:3000/api/devices";
//JSON Construction
var deviceInstance = {
"manufacturer": "manufacturer",
"model": "model"
//etc
}
// NPM (request)
request({
url: api,
method: "POST",
headers: {"Accept: application/json"},
json: true,
body: deviceInstance
}, function (error, response, body) {
if(error) {
console.log('error: '+ error);
} else {
console.log('document saved to api')
console.log(body);
console.log(response);
}
//request is done, we can safely exit
process.exit();
});
在request
的回调中调用exit()
函数将有效地确保POST请求已完成,您可以安全地退出。
事实上,您不需要手动退出:一旦事件循环为空,任何Node进程都会自行退出。 换句话说,一旦没有为进程安排进一步的任务,节点就自己退出进程。
您可以在官方文档中找到有关此内容的更多信息: https : //nodejs.org/api/process.html#process_event_exit
request
需要回调:
request({
url: api + "Devices",
method: "POST",
headers: "Accept: application/json",
json: true,
body: JSONParent
}, (err, result, body) => {
// do your stuffs with the results
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.