iJade
iJade

Reputation: 23811

Calling a web service using nodejs

I'm quite new to Node.js. I was experimenting with how to call a service using NodeJS. Would be helpful if could point out the NodeJS equivalent of the code below:

$.ajax({
  type: "POST",
  url: "/WebServiceUtility.aspx/CustomOrderService",
  data: "{'id': '2'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (message) {
    ShowPopup(message);
  }
});

Any helpful links would be most appreciated.

Upvotes: 28

Views: 65487

Answers (3)

Chris Tavares
Chris Tavares

Reputation: 30411

The easiest way at the moment is to use the Request module (deprecated since 2020). See the page there for lots of examples showing how to do what you want.

If you want to use raw node.js, you'll need to use either http or https built-in modules, but you'll have to handle a lot of the encoding and streaming details yourself. Also, be sure to look specifically at the client parts of the documentation, not the server.

Upvotes: 14

Akash Khapare
Akash Khapare

Reputation: 31

//--------- Tracking request service                  
factory.trackRequest = function (payload) {
    return $http({
        method: 'POST',
        **url: 'https://uat-userauthentication.bdt.kpit.com/'+ 
 'employee/trackRequestStatus'**,
        data: payload
    });
 };

 return factory;

I call node js service in angular by UI routing and I used trackRequest function in controller.

Upvotes: 0

hexacyanide
hexacyanide

Reputation: 91769

The Node.js equivalent to that code can be using jQuery server-side, using other modules, or using the native HTTP/HTTPS modules. This is how a POST request is done:

var http = require('http');
var data = JSON.stringify({
  'id': '2'
});

var options = {
  host: 'host.com',
  port: '80',
  path: '/WebServiceUtility.aspx/CustomOrderService',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
    'Content-Length': data.length
  }
};

var req = http.request(options, function(res) {
  var msg = '';

  res.setEncoding('utf8');
  res.on('data', function(chunk) {
    msg += chunk;
  });
  res.on('end', function() {
    console.log(JSON.parse(msg));
  });
});

req.write(data);
req.end();

This example creates the data payload, which is JSON. It then sets up the HTTP post options, such as host, port, path, headers, etc. The request itself is then set up, which we collect the response for parsing. Then we write the POST data to the request itself, and end the request.

Upvotes: 30

Related Questions