Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS express make get request

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.

like image 214
marcel Avatar asked Jun 12 '14 14:06

marcel


People also ask

What is get () in Express?

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 .

How do you use handle GET request in Express js?

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.


2 Answers

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.
  }
})
like image 168
Denys Séguret Avatar answered Oct 11 '22 16:10

Denys Séguret


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);
like image 27
Luke Avatar answered Oct 11 '22 16:10

Luke