Search code examples
javascriptnode.jsjsonmongodbloopback

Trying to post data with Request NPM from NodeJS to localhost (Loopback Swagger API)


When I try to post an instance to loopback from within nodejs using this code I don't get any errors but I don't get any data posted either?

//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();

I'm not getting any response or erros from the server which is the same machine. If I try the same call in postman (windows app) it actually creates an instance in the API so why isn't my local node connecting to the API?


Solution

  • Why process.exit() ?

    Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending.