codeofnode codeofnode - 3 months ago 10
Javascript Question

How can I make AJAX requests using the Express framework?

I want to send AJAX requests using Express. I am running code that looks like the following:

var express = require('express');
var app = express();

app.get('/', function(req, res) {
// here I would like to make an external
// request to another server
});

app.listen(3000);


How would I do this?

Answer

You don't need Express to make an outgoing HTTP request. Use the native module for that:

var http = require('http');

var options = {
  host: 'example.com',
  port: '80',
  path: '/path',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': post_data.length
  }
};

var req = http.request(options, function(res) {
  // response is here
});

// write the request parameters
req.write('post=data&is=specified&like=this');
req.end();
Comments