Reputation: 3272
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.
Upvotes: 14
Views: 47091
Reputation: 20070
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);
Upvotes: 7
Reputation: 382454
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.
}
})
Upvotes: 37