Node. A hands on guide to using the Express framework for js

  • 2021-01-25 07:10:33
  • OfStack

Express introduction
npm provides a large number of third side modules, including many Web frameworks, such as the lightweight Web framework described in this chapter, Express.

Express is a concise, flexible node js Web application development framework, it provides a series of powerful features, such as: the template parsing, static file services, middleware, routing control and so on, and you can also use the plug-in or integrate with other modules to help you to create various Web and mobile applications, is by far the most popular based on Node js Web development framework, and support the Ejs, a variety of templates, such as jade can quickly build a website with complete functions.

Okay, let's get started!

1. NPM installation


npm install express

2. Acquisition and reference


var express = require('express');
var app = express();

With the variable "app", we can call various methods of express. The fun has just begun. Keep going!

Create an
With the Express framework in mind, we started to create our first express application.

Add the following to our default project main file app.js:


var express = require('express');
var app = express();
app.get('/', function (request, response) {
  response.send('Hello World!');
});

app.listen(80);

Note: In the rest of the course, we will use port 80 to listen for requests.

After adding it, look at the browser content through the "Test address" on the right sidebar. When you see "Hello World!" The content indicates that a simple express application has been created successfully.

get request
In front of us to achieve a simple express application, let's begin to describe the specific implementation of it, first of all, we first to learn the common methods of Express.

get method - handles GET requests from clients according to the request path.

Format:


app.get(path,function(request, response));

path is the path of the request. The second parameter is the callback function to process the request. There are two parameters, request and response, which represent the request information and the response information.

Here's an example:


var express = require('express');
var app = express();

app.get('/', function(request, response) {
  response.send('Welcome to the homepage!');
});
app.get('/about', function(request, response) {
  response.send('Welcome to the about page!');
});
app.get("*", function(request, response) {
  response.send("404 error!");
});
app.listen(80);

In the example above, the about page path, root path, and handling of all paths are specified. And inside the callback function, use the send method that HTTP responds to, which means sending a string to the browser.

Referring to the above code, try to set up an get request path yourself, and then the browser can visit this address to see if the request is successful.

Middleware < The middleware >
1. What is middleware?

Middleware (ES86en) is the function that handles ES87en requests to perform various specific tasks, such as checking whether the user is logged in, analyzing the data, and other tasks that need to be done before the data needs to be finally sent to the user. Its biggest feature is that after processing by one middleware, the corresponding data can be passed to the next middleware.

2.1 middleware that does nothing but pass request objects, which looks something like this:


function Middleware(request, response, next) {
  next();
}

The next of the above code is the middleware callback function. If it takes an argument, an error is thrown, with the argument being the error text.


function Middleware(request, response, next) {
  next(' Make a mistake! ');
}

After the error is thrown, subsequent middleware will not execute until an error handler is found. If the next method is not called, the subsequent registered function will not execute.

Basic usage of the all function
The app.all () function matches all ES106en verbs, which means that it filters all paths of requests. If the middleware is defined using the all function, then all requests must pass through this middleware first.

Format:


app.all(path,function(request, response));

As shown below, we use the all function to set the response header properties before the request.


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

app.all("*", function(request, response, next) {
  response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" }); // Sets the response header property value 
next();
});

app.get("/", function(request, response) {
  response.end(" Welcome to the home page !");
});

app.get("/about", function(request, response) {
  response.end(" Welcome to about page !");
});

app.get("*", function(request, response) {
  response.end("404 -  Not found !");
});

app.listen(80);

The "*" in the code argument above means that it is valid for all paths. This method is particularly useful when dealing with a particular prefix path or any path, and any path we request will go through the all function beforehand.

If so, what if we skip the all function and try it ourselves?

use Basic Usage 1
use is a method express calls the middleware and returns a function.

Format:


app.use([path], function(request, response, next){});

// Optional parameters path The default is "/" . 

1. Use middleware


var express = require('express');
var app = express();
0

As mentioned above, we use the use function to call the express middleware to set the access path to the static file directory (the root path is assumed here).

2. How to call two middleware in succession, as shown in the following example:


var express = require('express');
var app = express();

app.use(function(request, response, next){
 console.log("method : "+request.method+" ==== "+"url : "+request.url);
 next();
});

app.use(function(request, response){
 response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
 response.end(' Example: Two middleware calls in a row ');
});

app.listen(80);

The next parameter of the callback function means that the call from other middleware is accepted, and the next() in the function body means that the request data is passed to the next middleware.

The above code first calls the first middleware, outputs a line of information on the console, and then calls the second middleware through next(), outputs HTTP response. Since the second middleware did not call the next method, the req object is no longer passed backwards.

use Basic Usage 2
The use method can not only call the middleware, but also return different web page content depending on the requested URL, as shown in the following example:


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

app.use(function(request, response, next) {
  if(request.url == "/") {
    response.send("Welcome to the homepage!");
  }else {
    next();
  }
});

app.use(function(request, response, next) {
  if(request.url == "/about") {
    response.send("Welcome to the about page!");
  }else {
    next();
  }
});
app.use(function(request, response) {
  response.send("404 error!");
});
app.listen(80);

The code above uses the request. url attribute to determine the requested URL and return different content.

The callback function
The Express callback takes two parameters, request(req for short) and response(res for short). request represents the HTTP request sent from the client, and request represents the HTTP response sent to the client. Both parameters are objects. Examples are as follows:


var express = require('express');
var app = express();
3

In the following study, we will often deal with it, keep in mind its format!

Get hostname, path name
Today we'll start by learning how to use req objects to handle HTTP requests from clients.

req. host returns the hostname (not including the port number) taken in the header of the request.

req.path returns the path name of the requested URL.

Here's an example:


var express = require('express');
var app = express();
4

Try 1 to enter any one of the request paths in the browser and see the hostname or request path through req.

query Basic usage
query is an object property that can retrieve client get request path parameters. It contains the parsed request parameter object, default {}.


var express = require('express');
var app = express();
5

req.query Gets the object parameter values of the get request path via req.query.

Format: req.query. Parameter name; The request path is as follows:

Case 1: / search & # 63; n=Lenka


var express = require('express');
var app = express();
6

Case 2: / shoes & # 63; order=desc & shoe[color]=blue & shoe[type]=converse


req.query.order // "desc"

req.query.shoe.color // "blue"

req.query.shoe.type // "converse"

Try 1 get request a path with arguments, using "req.query. The Parameter Name method gets the request parameter values.

param Basic usage
Like the query1 property, using req. param we can also get the value of the parsed request parameter object.

Format: req. param(" parameter name "); The request path is as follows:

Example 1: Gets the parameter value of the request root path, such as /? n=Lenka;


var express = require('express');
var app = express();

app.get("/", function(req, res) {

  console.log(req.param("n")); //Lenka

  res.send(" use req.param Property gets the parameter object value of the request root path !");

});
app.listen(80);

Example 2: We can also get the request object with the corresponding routing rule. Suppose the routing rule is /user/:name/, and the request path is /user/mike, as follows:


var express = require('express');
var app = express();
9

PS: The so-called "route" means to specify different processing methods for different access paths.

Looking at the above example, try 1 to resolve a request path object using the req. param property and get the request parameter values.

params basic usage
params is similar to param, but params is a property that can resolve request objects containing complex named routing rules.

req.params. Parameter name;

Example 1. For the example of requesting the root path in the previous class, we can obtain it as follows:


var express = require('express');
var app = express();

app.get("/user/:name/", function(req, res) {
  console.log(req.params.name); //mike
  res.send(" use req.params Property to get the value of a parameter object with routing rules !");
});

app.listen(80);

The param attribute function is the same as that of the param attribute.

Example 2: of course we can also request the complex routing rules, such as/user: name / : id, assuming that the request address is: / user/mike / 123, are as follows:


app.get("/user/:name/:id", function(req, res) {
  console.log(req.params.id); //"123"
  res.send(" use req.params Property of a parameter object value for a complex routing rule !");
});

For request addresses with routing rules for the path, the params property is not more powerful than the param property then 1 dot!

send basic usage
The send() method sends one response message to the browser and handles different types of data intelligently. Format is as follows: res. send ([body | status], [body]);

1. Content-Type is set to "text/html" by default when the parameter is 1 String.


res.send('Hello World'); //Hello World

2. When Array or Object is used, Express will return 1 JSON.


res.send({ user: 'tobi' }); //{"user":"tobi"}
res.send([1,2,3]); //[1,2,3]

3. When the parameter is 1 Number and no one of the above is in the response body, Express will set a response body for you. For example, 200 will return the character "OK".


res.send(200); // OK
res.send(404); // Not Found
res.send(500); // Internal Server Error

The send method automatically outputs a response with a few Settings, such as HEAD information, HTTP cache support, and so on.


Related articles: