简体   繁体   English

如何使用节点向外部API发出带有JSON有效负载的发布请求?

[英]How do I make a post request with a JSON payload to an external API using node?

I am trying to make a POST request with a JSON payload to an external API using node. 我正在尝试使用节点向外部API发出带有JSON有效负载的POST请求。

Here is my code: 这是我的代码:

var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var url = require("url");
var http = require("http");

var app = express();

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/api', function(req, res) {
  var query = url.parse(req.url, true).query;
  var key = query.key;

  console.log('JSON PAYLOAD:');
  console.log(req.body); **//PAYLOAD COMES THROUGH AS EXPECTED**

  var options = {};

  options = {
    host: 'localhost',
    port: 1234,
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    path: '/api?key=1234'
  };

  var request = http.request(options, function(response) {
    response.setEncoding('utf-8');
    var responseString = '';
    response.on('data', function(data) {
      responseString += data;
    });
    response.on('end', function() {
      var resultObject = JSON.parse(responseString);
      res.json(resultObject);
    });
  });

  request.on('error', function(e) {
  });

  request.write(req.body) **//THIS METHOD SHOULD BE FORWARDING THE PAYLOAD BUT THIS IS NOT THE CASE...**
  request.end();
});

The JSON payload comes through as expected from the origin. JSON有效负载如预期般从来源通过。 However I am unable to forward this payload to the external API. 但是,我无法将此有效载荷转发到外部API。 'request.write(req.body)' appears to be the way to do this, however the external API is still receiving a null payload. 'request.write(req.body)'似乎是实现此目的的方法,但是外部API仍在接收空有效负载。

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

Try this Inside the app.post block 在app.post块内尝试

 var options = { host: 'localhost', path: '/api?key=1234', port: 1234, method: 'POST', headers: {'Content-Type': 'application/json'} }; callback = function(response) { var str = '' response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { console.log(str); }); } var req = http.request(options, callback); req.write(JSON.stringify(req.body)); req.end(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM