0

I want to use the request module in my express app, but I am not sure where the actual requests code goes.

Usage:

  • When a user loads a page, make a GET request and populate the page with data.
  • When a users clicks on a item from a table, make a GET request.
  • When a user fills out a form, POST.

I tried searching for answers but it seems to be implied that the developer knows where to place the code.

Example of a code snippet using request that I am unsure where to place in the express app:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage. 
  }
})

I am guessing that I should not place the code in the server.js file especially if I am going to be making many different calls, but that's what it looks like others are doing on StackOverflow.

Does the request belong in a model?

Community
  • 1
  • 1
anonameuser22
  • 108
  • 12

1 Answers1

0

If you are doing this in response to a user interaction, like clicking on something you can just do it from the route handler. Below, I just return the results to the client, or I pass an error to the next handler in the chain.

var request = require('request');
var express = require('express');
var app = express();

app.get('/click', function(req, res, next){
    request('http://www.google.com', function (error, response, body) {
      if (error || response.statusCode != 200)
        return next(err);
      response.send(body) // return the html to the client
    })
});

app.listen(3000);

In bigger apps you might move routes into separate modules.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86