尝试使用Request NPM将数据从NodeJS发布到本地主机(Loopback Swagger API)

时间:2019-02-05 08:16:16

标签: javascript node.js json mongodb loopback

当我尝试使用此代码从Node.js中发布实例以进行回送时,我没有收到任何错误,但也没有发布任何数据?

//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?

3 个答案:

答案 0 :(得分:1)

为什么 process.exit()

调用process.exit()将强制进程尽快退出,即使仍有异步操作挂起。

答案 1 :(得分:1)

会发生什么,为什么

您看到的行为是由于Javascript的异步性质。

您的代码从上至下启动 POST请求,然后在请求完成之前调用process.exit(),这将使您看到行为并“破坏”您的代码

从那里有两个解决方案:

在请求的回调中调用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请求,并且可以安全退出。

完全删除process.exit()

事实是,您无需手动退出:事件循环为空后,任何Node进程都会自行退出。换句话说,一旦不再为该进程安排任何任务,节点就会自行退出该进程。

您可以在官方文档中找到关于此的更多信息:https://nodejs.org/api/process.html#process_event_exit

答案 2 :(得分:0)

request需要回调:

request({
  url: api + "Devices",
  method: "POST",
  headers: "Accept: application/json",
  json: true,
  body: JSONParent
}, (err, result, body) => {
  // do your stuffs with the results
});