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)
Solution 1:
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.
}
})
Solution 2:
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();
Solution 3:
Since you are simply making a get request I suggest this https://nodejs.org/api/http.html#http_http_get_options_callback
var http = require('http');
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
if(res.statusCode == 200) {
console.log("Got value: " + res.statusMessage);
}
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
That code is from that link
Post a Comment for "How Can I Make AJAX Requests Using The Express Framework?"