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?
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.
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.
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.
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With