Express.js Overview and the Core http RESTful API Demo

Welcome to the Node Program. This lesson is about Express.js. So, if you're not familiar with Express.js completely, it's a web framework based on Node.js technology that delivers a static content, similar to Apache or NGINX, but it also could be used for dynamic content such as an API and web apps.

You can also easily modularize your business logic and connect to various data sources and use many many Express.js logins which are called middleware with it. It's the most popular web framework based on Node.js. But before we start with Node.js, let's take a look at this demo. I will show you a small restful API built with just the core http module, so you can really see what is possible to do with just the core modules, without any frameworks, but also you would see how much work it is to use that code without any frameworks.

So if you click that link in the slides, you will get to the GitHub repository, I already have this folder on my machine, and I open it in my favorite editor, Atom. So first of all we import a lot of modules. Most of them are core modules except MongoDB. And then we use createServer with just a single callback.

And as you can see, we have three routes or three request handlers inside of this callback, and its options, which is for course origin resource sharing, when you have your client or single page application located on a different domain, you would need to implement options.

Then I'm using if else condition, and I'm processing request that method against the get value, because this is a get request, to the /messages/list.json. So this will get me the list of messages and I'm building a message board api. So far so good, I have only two if else conditions, and insides of my depth, I need mainly only write headers because the core module would not do that for me, so I'm writing content type and content length.

Then we can move to the next route which is post/messages/create.json. This route will take the request data past the body by using JSON.parse, and a good idea would be, actually, to rub this call, JSON.parse, in a try catch, because every time you have the wrong symbol, this will crash the app, and for the clients, you might know that would happen very often.

Okay, so what else is going on here? JSON.stringify, we need to stringify the object after we've saved it to the database so we can send it back, and obviously again we need to write the headers, content type and length.

So you might think that's not a big deal, I can write the headers, maybe I can create a function, obstruct it, and also same with the parse-ing, I can also obstruct that and reuse that code, and then basically what will happen, you will adapt with your own framework. So instead of creating your own framework and then spending a lot of time on its maintenance, why not use something that has already been tested? It's mature enough, and it's stable, something like Express.js.