在 node.js 应用程序中发出 post 请求

make a post request with in node.js application

我有一个带有 /api/authenticate 端点的 node.js 服务。我可以使用 'username' 和 'password' 作为输入(正文参数)从 POSTMAN 成功调用此服务。如何从另一个 node.js 服务器调用相同的服务?

我得到了邮递员,

body: {name: 'xxxxxx', password: 'xxxxxx' }
headers: { 'content-type': 'application/x-www-form-urlencoded',
  host: 'xx.xx.xx.xx:xxxx',
  connection: 'close',
  'content-length': '0' }

POST /api/authenticate 200 1.336 毫秒 - 72

以下是另一个 nodejs 应用程序...它发出成功的请求调用,但在到达身份验证服务器时没有任何正文参数(用户名和密码)api。

var my_http = require('http');

app.get('/makeacall', function(req, res) {
  var output = '';
  var options = {
    body: { name: 'xxxxxx', password: 'xxxxxx' },
    method: 'POST',
    host: 'xx.xx.xx.xx',
    port: 'xxxx',
    path: '/api/authenticate',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  };

console.log('before request');

var req = my_http.request(options, function(response) {
  console.log('response is: ' + response);
  console.log('Response status code: ' + response.statusCode); 
  response.on('data', function(chunk) {
   console.log('Data ..');
   output += chunk;
  });
  response.on('end', function(chunk) {
   console.log('Whole Data ..' + output);
  });

});
req.on('error', function(err) {
  console.log('Error: ' + err);
});
req.end();
console.log('444');
res.send({ message: 'View record message'});

});

从这个 nodejs 应用程序,我在服务器上得到了空体。

body: {}
headers: { 'content-type': 'application/x-www-form-urlencoded',
  host: 'xx.xx.xx.xx:xxxx',
  connection: 'close',
  'content-length': '0' }
POST /api/authenticate 200 1.336 ms - 72

我错过了什么?感谢任何帮助。

您是否正在尝试从 form/etc 获取发布的数据?

尝试使用快递。

npm install express -save

您可以使用 ff:

从 url 获取发布的数据
app.post('*', function(request, response){  
    var post = {};
    if(Object.keys(request.body).length){
        for(var key in request.body){
            post[key] = request.body[key];
            console.log(key+'=>'+post[key];
        }
    }
});

使用 NodeJS 的标准 http 库不允许您使用该语法。

看看 RequestJS 作为更简单的解决方案。它会让你的生活更轻松,并允许你使用你想要的语法。

这是使用 stock Node 的解决方案。

https://nodejs.org/api/http.html#http_http_request_options_callback

相关部分:

var postData = querystring.stringify({
  'msg' : 'Hello World!'
});

然后,最后:

// write data to request body
req.write(postData);
req.end();

但除非绝对不行,否则请使用图书馆。