Express

If you're familiar with Node.js, you probably know of one module that is the core for most Node.js platforms and applications that are around. You have probably heard of Express, and it's not by accident. It's eight years old and it's been there since the beginning of Node.js.

Express is a rock-solid layer that helps you create applications faster. As it states on its website, it's a fast, unopinionated, and minimalist web framework.

Node.js has an HTTP module that you can use to create a simple HTTP server. The problem is that it's too raw and you'll have to do a ton of work so that you can make it usable and modular. Instead of you creating that layer, you can use Express.

To install Express, create a folder and run the following command:

npm init –y
npm install express ––save

Then, create a file called app.js and place the following code inside it:

let express = require("express");
let app = express();

app.get("/", (req, res) => {
res.send("Hello World");
});

app.listen(80);

Then, run your code using the following command:

node app

Go to your browser and type the address http://localhost:3000/. You should see something like the following:

With Express, you can associate functions to routes. A route is a URL with a specific HTTP verb, but it doesn't necessarily have to. You can have automatic parameters parsing inside routes. You can even associate more functions to the same route and have them be called sequentially. You can also stop the sequence at any time. It's up to you; remember, Express is not opinionated.

Change your app.js to the following code and run it again:

let express = require("express");
let app = express();
let stack = [];

app.post("/stack", (req, res, next) => {
let buffer = "";

req.on("data", (data) => {
buffer += data;
});
req.on("end", () => {
stack.push(buffer);
return next();
});
});

app.delete("/stack", (req, res, next) => {
stack.pop();
return next();
});

app.get("/stack/:index", (req, res) => {
if (req.params.index >= 0 && req.params.index < stack.length) {
return res.end("" + stack[req.params.index]);
}
res.status(404).end();
});

app.use("/stack", (req, res) => {
res.send(stack);
});

app.listen(3000);

You'll have trouble testing it in the browser because we're using POST and DELETE verbs. Instead, let's use curl and make requests in the command line. Follow this sequence and see if you understood the preceding code:

We first make a request to /stack just to see if it will return an empty array. Then, we use --data to pass zero as the HTTP request body and curl assumes it's a POST. We do it again, this time, with body one. For both requests, we get the final stack result. We then request stack index 1 and it returns one. We then request index 2 and, as you can see by the -v parameter, our code returns a proper 404 Not Found error.

You might have wondered how the stack is returned on both GET and POST requests and that's the reason for calling next(), which tells Express to pass to the next route (if there are any) available. In our case, it's the route that's been defined that's using the use method. This is a catch all for all HTTP verbs. Remember: route definition order is important and that's why the catch all is done at the end.

As you can see, we can scale pretty fast to complex logic. It's important to note that although Express really helps you create an HTTP service easier, it's still just an improved layer over the http and https modules that are available.

To help you even more, it has an integrated modular system, called middleware, and hundreds of compatible published modules that help you create services even faster, such as session handling, templating, caching, and security modules.

Let's make our example a little bit more complex so that you can see what I mean. First, install some middleware:

npm i body-parser --save

Now, change your code to this:

let express = require("express");
let body = require("body-parser");
let route = express.Router();
let app = express();
let stack = [];

app.use(body.text({ type: "*/*" }));

route.post("/", (req, res, next) => {
stack.push(req.body);

return next();
});

route.delete("/", (req, res, next) => {
stack.pop();

return next();
});

route.get("/:index", (req, res) => {
if (req.params.index >= 0 && req.params.index < stack.length) {
return res.end("" + stack[req.params.index]);
}
res.status(404).end();
});

route.use((req, res) => {
res.send(stack);
});

app.use("/stack", route);
app.listen(3000);

It has the same number of lines, but we improved our code by making two important changes:

  • Instead of reading the request body, we now use a middleware, body-parser, which handles it for us and supports several body types and compression.
  • We created an express.Route and attached it to our service at the last but one line. We can use this to move our route definition to a separate file and make it URL agnostic (see how we only mention /stack once, when attaching).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset