简体   繁体   中英

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.

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. However I am unable to forward this payload to the external API. 'request.write(req.body)' appears to be the way to do this, however the external API is still receiving a null payload.

Any help would be appreciated. Thanks.

Try this Inside the app.post block

 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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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