It’s Magic: ExpressJS Server < 10 Lines

Aka ExpressJS and Node frameworks rule and I am never using any native Node modules again

Express is to NodeJS as JQuery is to Javascript. There’s so many native functions within Node that are pretty arcane to use. Having gone through the trouble of building a server from scratch in Node, I now so much more deeply appreciate frameworks like Express.

So many things I love in life that have the word “express” in it. Panda Express, ExpressJS. Actually… those are probably the only two things.

In order to give you another tutorial of how amazing Express is compared to creating a server with the native Node modules, I will create a server in Express in < 10 lines.

1. Install ExpressJS

In your terminal, use npm to install the Express library and save it as a dependency to use in your server.

$ npm install express --save

2. Create the server

  • You want to require the Express module you just saved from npm
  • Express uses middleware functions (more on this at the end) in order to deal with various requests to the server — if this seems like a bit of wizardry in comparison to what we saw with the HTTP Node module, it’s because it is!
var express = require('express');
var app = express();
app.get('/', function(request, response) {
response.send('Wingardium Leviosa');
});

3. Make sure the server is listening

  • Give it a port number to listen on. 3000, 1337, etc. I decided on 4568 for this example.
app.listen(4568, function () {
console.log('Example app listening on port 4568!');
});
Important note: The app starts a server and listens on the port for connections. The app responds with “Wingardium Leviosa” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.

What is middleware?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next. — ExpressJS Docs”

Basically, these are amazing instruments used to simplify your server response process. Whether this is dealing directly with basic HTTP requests in your app or maybe you want to use it to restrict access to authenticated users using the Express Session middleware. Here are some great examples:

/* A BASIC POST HTTP REQUEST */
app.post('/', function (req, res) {
res.send('Got a POST request');
});
/* Using Express Session Middleware to Add Sessions to Incoming HTTP Requests */
app.use(session({ 
secret: 'keyboard cat',
resave: false,saveUninitialized: true,
cookie: { secure: true }
}));

Hope this is a great start for your Express servers. Happy Expressing!!!