What does Express.js do in the MEAN stack?

I have recently have gotten into AngularJS and I love it. For an upcoming project I am looking to use the MEAN stack (MongoDB, Express, Angular, Node). I'm pretty familiar with Angular and I have a modest understanding of the purposes of MongoDB and Node in the stack. However, I don't really understand what the purpose of Express.js is. Is it essential to the MEAN stack? What would you compare it to in a traditional MySQL, PHP, javascript app? What does it do that the other three components can't do?

Also, if someone wants to give their own take on how the four parts of the stack work together, that'd be great.


Solution 1:

  • MongoDB = database
  • Express.js = back-end web framework
  • Angular = front-end framework
  • Node = back-end platform / web framework

Basically, what Express does is that it enables you to easily create web applications by providing a slightly simpler interface for creating your request endpoints, handling cookies, etc. than vanilla Node. You could drop it out of the equation, but then you'd have to do a lot more work in whipping up your web-application. Node itself could do everything express is doing (express is implemented with node), but express just wraps it up in a nicer package.

I would compare Express to some PHP web framework in the stack you describe, something like slim.

Solution 2:

You can think of Express as a utility belt for creating web applications with Node.js. It provides functions for pretty much everything you need to do to build a web server. If you were to write the same functionality with vanilla Node.js, you would have to write significantly more code. Here are a couple examples of what Express does:

  • REST routes are made simple with things like
    • app.get('/user/:id', function(req, res){ /* req.params('id') is avail */ });
  • A middleware system that allows you plug in different synchronous functions that do different things with a request or response, ie. authentication or adding properties
    • app.use(function(req,res,next){ req.timestamp = new Date(); next(); });
  • Functions for parsing the body of POST requests
  • Cross site scripting prevention tools
  • Automatic HTTP header handling
    • app.get('/', function(req,res){ res.json({object: 'something'}); });

Generally speaking, Sinatra is to Ruby as Express is to Node.js. I know it's not a PHP example, but I don't know much about PHP frameworks.