Is there a possibility to use express as a client-module, to make http-requests to another server?
At the moment I make requests this way:
var req = http.get({host, path}, function(res) {
res.on('data', function(chunk) {
....
}
}
This is too bulky. Express as server-module is very comfortable to use. I guess there's a simple way to make a get-request by using express. I don't like the express api, and I didn't find anything there.
Express' app. get() function lets you define a route handler for GET requests to a given URL. For example, the below code registers a route handler that Express will call when it receives an HTTP GET request to /test .
get() method of the express. js is used to handle the incoming get request from the client-side Basically is it intended for binding the middleware to your application. Parameters: path: It is the path for which the middleware function is being called.
If you want simple requests, don't use the express module, but for example request :
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
})
The answer to use request
is a bit dated, seeing as it has been deprecated since 2019.
Using Node's built-in https.request()
method (node documentation) does feel a bit "bulky" (IMO), but you can easily simplify it for your needs. If your use case is as you describe, then all you need is:
function httpGet(host, path, chunkFunction) {
http.get({ host, path }, (res) => res.on('data', chunkFunction));
}
Then implement it everywhere like:
const handleChunk = (chunk) => { /* ... */ };
const req = httpGet(host, path, handleChunk);
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