3

i have this in my server.js

app.post("/leadAPI/ed",function(request,response){
//api post code here
});

In this post request i need to post data contained in request body to some external API with a specific URL and send the response back using response.send. How to do it in a clean fashion. Is there anything build in for this in expressjs?

beNerd
  • 3,314
  • 6
  • 54
  • 92

3 Answers3

6

As Andreas mentioned, this isn't express's duty. Its duty is to invoke your function when an HTTP request comes in.

You can use node's built-in HTTP client, as Andreas also mentioned in a comment, to make a request to your external site.

Try something like this:

var http = require('http');

app.post("/leadAPI/ed", function(request, response) {
  var proxyRequest = http.request({
      host: 'remote.site.com',
      port: 80,
      method: 'POST',
      path: '/endpoint/url'
    },
    function (proxyResponse) {
      proxyResponse.on('data', function (chunk) {
        response.send(chunk);
      });
    });

  proxyRequest.write(response.body);
  proxyRequest.end();
});

I'm sure you'll need to adapt it to handle chunked responses and figure out the transfer-encoding, but that is the gist of what you need.

For details, see

http://nodejs.org/api/http.html

Brandon
  • 9,822
  • 3
  • 27
  • 37
  • how do i post some fields with the above method? like say i want to send value of firstname via post method to the api url...where do i do that? – beNerd Mar 15 '13 at 05:13
  • Then change the response.body reference in proxyRequest.write to write an object that you construct yourself. You didn't specify you wanted a sub-set of the original request data, so I used response.body to get the entire thing. – Brandon Mar 17 '13 at 16:09
5

I would use Mikeal Rogers' request library for this:

var request = require('request');

app.post("/leadAPI/ed",function(req, res){
  var remote = request('remote url');

  req.pipe(remote);
  remote.pipe(res);
});
Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
  • @mikeal what does these two lines mean req.pipe(remote); remote.pipe(res); – fokosun Apr 15 '17 at 15:58
  • @Picrasma request uses the nodejs Stream api, which is great for this kind of stuff. See the [documentation on stream.pipe()](https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options) in particular. Basically, it will write the request body to the remote URL as it gets written, and write the remote response to the response as it gets read. – Linus Thiel Apr 16 '17 at 19:39
1

You could do it like this.

var request = require('request');
var url = "<remote url>"
app.post("/leadAPI/ed",function(request, response){
  request.get({url:url, headers:request.headers, body:request.body}, function (err, res, body) {
    if(!err) {
      response.status(200).send(res) // JSON.stringify(res) if res is in json
    }
  })
})

Remember, content-type should be same for both.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
pride
  • 85
  • 1
  • 11