Whoami
Whoami

Reputation: 14408

Unable to invoke REST from node.js which works if I invoke from browser?

I am trying to invoke WebServer [ mongoose embedded webserver] which is running in another machine.

Below is the code.

var express = require('express');
var http = require ('http');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});


router.get ('/start', function (req, res) {
   res.render('start',  { title: 'Hello, World!' });
});

router.get ('/startAction', function (req, res) {
   jsonObject = JSON.stringify ({
   "n1" : 8,
   "n2" : 10
   }); // jSon Data.
   var postheaders =  {
      'content-Type' : 'application/json',
      'content-Length' : Buffer.byteLength(jsonObject, 'utf8')
   }
   var optionspost = {
       host : "http://192.168.6.120/",
       port : 5432,
       path : "/api/sum",
       method : "POST",
       headers : postheaders
   };
   console.log ("Invoking Restful API"); 
   var reqPost = http.request(optionspost, function(res) {
      console.log ("status code ", res.statusCode);
   res.render('start',  { title: 'Send some result of Request..' });
   }); 

});
module.exports = router;

The error what i am getting is..

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: getaddrinfo ENOTFOUND
    at errnoException (dns.js:37:11)
    at Object.onanswer [as oncomplete] (dns.js:124:16)

But, the same request works if i do from the html page.

<script language="javascript" type="text/javascript">
  jQuery(function() {

    $(document).on('keyup', '#n1, #n2', function() {
      $.ajax({
        url: '/api/sum',
        method: 'POST',
        dataType: 'json',
        data: { n1: $('#n1').val(), n2: $('#n2').val() },
        success: function(json) {
          $('#result').html(json.result);
        }
      });
    });

  });
</script>

I am very new to node.js and all. Kindly point out where the culprit is?

Upvotes: 0

Views: 99

Answers (1)

mscdex
mscdex

Reputation: 106698

This: host : "http://192.168.6.120/", should be: host : "192.168.6.120",.

Upvotes: 4

Related Questions