Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make HTTP Request To Self in NodeJS / ExpressJS

Tags:

I'm building an NPM module that needs to make an HTTP request to itself (the running web server). For example:

var url = "http://127.0.0.1:" + (process.env.PORT || 3000) + path; request(url, function(error, response, body){    ... }); 

Is there a way to process a request through the NodeJS pipeline without actually doing an HTTP request?

Or is there a better way to form the URL? I'm nervous that 127.0.0.1 isn't the most robust way to handle this for production sites.

like image 269
bendytree Avatar asked Aug 29 '13 16:08

bendytree


1 Answers

Self Consuming JSON API

In a self consuming JSON API, you define some functionality in some standalone controller functions and then wire the functionality up to express after the fact. Let's use a library application as an example:

books.js

module.exports = {   browse: function () {       return Book.findAll()   },   read: function (options) {       return Book.findById(options.book)   },   processLateFees: function () {       // Do a bunch of things to process late fees   } } 

to-http.js

In this file we build a function that converts a controller function to an HTTP route. We take the query params and pass that to our controller as options:

module.exports = function toHTTP (func) {     return function (req, res) {          func(req.params).then(function (data) {              res.send(data)          })     } } 

router.js

And then we connect up our controller to our http router

var express = require('express') var books = require('./books') var toHTTP = require('./to-http')  var app = express() app.get('/books', toHTTP(books.browse)) app.get('/books/:book', toHTTP(books.read)) app.get('/batch-jobs/process-late-fees', toHTTP(books.processLateFees)) 

So we now have an express application connected up to controller functionality. And the wonderful thing is that we can call these controller functions manually too.

var books = require('./books') books.processLateFees().then(function () {     // late fees have been processed }) 

If you need a more in depth example of this, the Ghost blog codebase is built around this pattern. It is a very informative read.

like image 117
JoshWillik Avatar answered Sep 19 '22 16:09

JoshWillik