27

我对 Node.js 很陌生。我正在试验如何使用 NodeJS 调用服务。如果能指出与以下代码等效的 NodeJS 将会很有帮助:

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

任何有用的链接将不胜感激。

4

3 回答 3

27

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.

于 2013-10-15T23:43:36.657 回答
14

目前最简单的方法是使用Request 模块。有关如何执行所需操作的示例,请参见那里的页面。

如果您想使用原始 node.js,则需要使用httphttps内置模块,但您必须自己处理大量编码和流式传输细节。此外,请务必特别查看文档的客户端部分,而不是服务器部分。

于 2013-10-15T23:27:36.963 回答
0
//--------- Tracking request service                  
factory.trackRequest = function (payload) {
    return $http({
        method: 'POST',
        **url: 'https://uat-userauthentication.bdt.kpit.com/'+ 
 'employee/trackRequestStatus'**,
        data: payload
    });
 };

 return factory;

我通过 UI 路由以角度调用节点 js 服务,并trackRequest在控制器中使用了函数。

于 2017-11-21T06:21:47.523 回答