当我尝试发布一个实例使用此代码,我没有得到任何错误内的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();
});
呼唤你exit()
的回调函数request
将有效地向你保证,POST请求完成后,你可以放心地离开。
事实是,你并不需要手动退出:任何节点进程自身一旦退出事件循环是空的。换句话说,一旦没有进一步的计划任务的过程中,节点退出自身的过程。
你可以找到关于本作的官方文档中的详细信息: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
});