Introduction to the

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

The trial scene

  1. Suitable for I/O intensive applications
  2. Suitable for front-end developers to quickly build servers, generally used for the separation of the front and back ends

Install Nodejs

windows

1. Go to nodejs.org.

2. ClickLTSVersion, download installation package,CurrentVersion is development version, do not download, as shownOnce the download is complete,Installed directlyCan be

ubuntu

Run the following command

    curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
    sudo apt-get install -y nodejs
Copy the code

mac

Similar to Windows, download the installation package

After the installation is complete, run the following command to check whether the installation is successful.

Node -v // Checking the Node version NPM -v // Checking the NPM versionCopy the code

Setting up the server

Install express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

NPM install express-g // Express is installed globally. NPM install express-generator-g // Express scaffolding is installed globally. After the installation, you can use the express command express --version // Check the Express versionCopy the code

Generate project files

Mkdir app CD app /** * generate project files * Express uses AJS templates by default, plus -e to specify friendlier EJS templates */ Express -e NPM intall // Install dependent NPM start // start projectCopy the code

Then the browser goes to localhost:3000 and the simplest server is ok.

Express advanced

How do I change the program startup default3000port

The Express startup directory is /bin/ WWW and contains one line of code:

var port = normalizePort(process.env.PORT || '3000');
Copy the code

PORT(the environment variable PORT); if not, the default value is 3000

So if you want to change the PORT number, you can directly change 3000 to the desired PORT number or change the value of the environment variable PORT as follows:

Before starting the program, execute

// ubuntu IOS
export PORT=4000;
// windows
set PORT=4000;
Copy the code

Then execute NPM start and the port is set to 4000.

How do I modify the operating environment

The Express default runtime environment is development. The runtime environment can be obtained from process.env.node_env. Set the system environment to production and the code is as follows:

// ubuntu IOS
export NODE_ENV=production
// wondows
set NODE_ENV=production
Copy the code

How to Add an Interface

In app.js, app.use(‘/’, routes); In front of the new

app.get('/status', function (req, res) {
       res.send({status: 'ok'});
})
Copy the code

Start server, go to localhost:3000/status, get data {status: ‘OK ‘}; App.get () is a method of the app object, which is responsible for handling the get method. If you change it to POST, only post requests are processed, and other requests are put and delete. If written as use, requests for any method of this route are processed. /status, which specifies the route callback function to process. That is, the handler that requested the route. It can take two arguments, three arguments, or four arguments. Any argument with four is considered an error handler by Express

/ / app. This is a mistake in js processing function, used to handle all routing thrown above errors, are written in the last app. Use (function (err, the req, res, next) {res. Status (err) status | | 500); res.render('error', { message: err.message, error: err }); });Copy the code

HTTP Request object encapsulated by REQ Express, including headers, Query, and Params attributes. The data used to retrieve an HTTP request. Res Express encapsulates HTTP reponse objects, including send, JSON, jSONP, and other methods. Next If you execute next, after executing this handler, it will go back to the next handler,

app.get('/test-next', function(req, res, next) {
       console.log('first handler fn');
       next();
});
app.get('/test-next', function(req, res, next) {
       res.send({status: 'second handler fn'});
}
Copy the code

Localhoat :3000/test-next: {status: ‘Second Handler fn’}, which handles the route /test-next, the first callback function, and next() to find the next callback that can handle /test-next.

What is middleware

Middleware (Middlewear) is an important concept in Express. Express uses middleware to modify the request body or perform intermediate operations. Ultimately, middleware is a function that satisfies two conditions,

  1. There arereq.res.nextThree parameters,
  2. The last executionnextFunction to hand over processing authority

Middleware for writing a print request:

Function logRequest(req, res, next) {console.log(req.method, method.url); next(); } // Use middleware app.use(logRequest);Copy the code

How does Express handle routing

For a request, Express processing goes through the process

1. Process the request from the first use or, if it is middleware, proceed from there

2. If the middleware encounters a static file, the system queries whether the static file matches. If the static file does not match, the system returns the static file.

3. If a customized route is matched, the callback function is executed immediately. If next() is not in the processing function, the callback function is not executed.

4. If none of them are matched, the server goes to the 404 processing middleware, which throws an error and sends it to the error processing middleware.

Understand static resource processing middleware

app.use(express.static(path.join(__dirname, ‘public’))); ,express.static(PATH) treats all resources in the specified directory as static resources. A client can enter the path of a specified resource to access it. In fact, it can be understood that the path of static resources is registered on the APP as a route. If you would have a file < project > / public/stylesheets/style.css. CSS, is set to the static resources, you can specify a static file directory

app.use(express.static(path.join(__dirname, 'public')));
Copy the code

You can also customize routes without setting static files

app.get('/stylesheets/style.css', function (req, res, next) {
        res.sendFile(path.join(__dirname, 'public/stylesheets/style.css'));
})
Copy the code

Two ways to access http://localhost:3000/stylesheets/style.css can get style.css. CSS file.

Static resources and user-defined routes are equivalent. Therefore, static resource processing middleware is generally placed in front of user-defined middleware to avoid route conflicts.

How to use templates (default ejS template engine)

// Path is the path of the ejS template. // Data is the value passed to the template, which must be the object type res.render(<path>, [data]);Copy the code

For example app. Js

app.get('/ejs', function(req, res, next) {
    res.render('index', { title: 'Express' });
});
Copy the code

index.ejs

<h1><%= title %></h1>
<p>test ejs</p>
Copy the code

Access localhost:3000/ EJS to see the result. The common syntax of EJS is as follows

1.<% %> You can write any javascript code inside the tag, either by breaking it apart or by combining it with an HTML tag:

<% var a = 1 var b = 2 var c = a+b %> // var user = [1,2,3] <% for(let I =0; i<user.length; i++) { %> <p> html </p> <% } %>Copy the code

2.<%= %> Displays the escaped content

// ejs <p><%= '<lol>' %></p>Copy the code

3.<%- %> Displays the unescaped content

/ / ejs < p > < % - '< a href = "http://www.baidu.com > baidu < / a >' % > < / p > / / not escape the output of the < p > < a href =" http://www.baidu.com > baidu < / a > < / p >Copy the code

4. < % # % > comments

Ejs = test.ejs = test.ejs = test.ejs = test.ejs = test.ejs = test.ejs = test.ejs

// exp1
<% var data = 1 %>
<% include ./test %>
 // exp2
<%- include('test', {data:1}) %>
Copy the code