Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make AJAX requests using the Express framework?

Tags:

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?

like image 374
codeofnode Avatar asked Sep 29 '13 05:09

codeofnode


People also ask

Is AJAX used with express?

expressjs is serverside code so it can't use jquery ajax like that. jQuery. ajax() can only be used at view when you load your page in the browser.

Which modern technique do you use to make an AJAX request?

We can use the XMLHttpRequest (also referred to as the XHR) object to communicate with the server. Using XHR object, a web page can interact with interact with PHP scripts, databases, applications and even text files located on the server.


1 Answers

You can use request library

var request = require('request');
request('http://localhost:6000', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Print the body of response.
  }
})
like image 102
Alexander Kobelev Avatar answered Sep 18 '22 22:09

Alexander Kobelev