Server.js
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var port = process.env.PORT || 8080; // set the port
var database = require('./config/database'); // load the database config
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===============================================================
mongoose.connect(database.localUrl); // Connect to local MongoDB instance. A remoteUrl is also available (modulus.io)
app.use(express.static('./public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
// routes ======================================================================
require('./app/routes.js')(app);
// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);
I understand a majority of this code. But I have never seen this:
require('./app/routes.js')(app);
I understand we are loading our routes but why are we passing (app) as if it is a function parameter? Why is this necessary and what would happen if I remove it?
The route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), an URL path/pattern, and a function that is called to handle that pattern. Node. js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. Node.
use is a way to register middleware or chain of middlewares (or multiple middlewares) before executing any end route logic or intermediary route logic depending upon order of middleware registration sequence. Middleware: forms chain of functions/middleware-functions with 3 parameters req, res, and next.
The req object represents the HTTP request and has properties for the request query string, parameters, body, and HTTP headers. The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
It just means that require('./app/routes.js')
returns a function.
You can then call this function with another set of parantheses.
It's basically the same as:
var func = require('./app/routes.js');
func(app);
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