繁体   English   中英

尝试使用Request NPM从NodeJS发布数据到localhost(Loopback Swagger API)

[英]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() ,从而提供您所看到的行为并“中断”您的代码。

从那里你有两个解决方案:

在请求的回调中调用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请求已完成,您可以安全地退出。

完全删除process.exit()

事实上,您不需要手动退出:一旦事件循环为空,任何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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM