This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Express framework

Express website

What is a Express

Express is a flexible Node.js Web application development framework that keeps scale to a minimum and provides a powerful set of capabilities for Web and mobile applications.

  • Express is a framework for building Web servers
  • Express retains the basic API of the HTTP module, which means that reQ and RES objects can also be used with Express
  • Express also encapsulates a few additional ways to make it easier to set up servers
  • Express provides middleware capabilities, and many other powerful third-party modules are based on Express

Construct the Web server using Express

// Download the express module
npm i express
Copy the code

Building a Web server using Express

  1. Loading the Express module
  2. Creating an Express server
  3. Starting a server
  4. Listen for browser requests and process them
// Target: Create and start the Web server and display the content in the browser

//1. Load the express module
const express = require('express');

//2. Create a server
const app = express();

//3. Start the server
app.listen(3000.() = > {
    console.log('express-server is running... ');
});

//4. Listen for browser requests
//app.post() to listen for post requests
//app.get() to listen for get requests

/ / when the url is: http://127.0.0.1:3000/index,
// Enter the following method to do the processing
// Parameter 1: URL address
// Argument 2: the callback function that is triggered when a browser request is listened to
// req: request object, which is the REQ object in the HTTP module
// res: response object, which is the RES object in the HTTP module
app.get('/index'.(req, res) = > {
    // The end method is also provided by the HTTP module
    res.end('Hello Express');
})

/ / when the url is: http://127.0.0.1:3000/list,
// Enter the following method to do the processing
app.get('/list'.(req, res) = > {
    // The send method is the method provided by express
    res.send('List page');
})

// All other addresses are processed below
app.get(The '*' , (req, res) = > {
    res.end('404 not found');
})
Copy the code

Conclusion:

  1. Building a server with Express is also a 4-step process:
① Load the Express moduleconst  express = require('express'); ② Create an Express serverconstapp = express(); (3) Open the Express server app. Listen (3000.() = >{}) app.get(url, callback) app.post(url, callback)Copy the code
  1. There are two methods to register server events: get() and POST ()
The GET method is used to receive GET requests. All requests initiated by the browser address bar are GET requests. The POST method is used to receive POST requests, requests submitted by the POST formCopy the code
  1. The Express framework encapsulates additional apis (such as Send) that make it easier to build Web servers
  2. Each URL requested by the browser is received and processed by a separate method. else if … Else, it’s a little bit more structured

routing

Simply put, routing is the relationship between the browser URL address and parameter 1 in app.get/app.post

Such as:

/ / browser address: http://127.0.0.1:3000/index

app.get('/index'.(req, res) = >{})Copy the code
/ / browser address: http://127.0.0.1:3000/goods/list

app.get('/goods/list'.(req, res) = >{})Copy the code

sendFile

Core: Use the sendFile method. This method is a method wrapped in Express that reads the file content directly and returns it to the browser

res.sendFile(var1, var2, var3);
/** Parameter 1: the path of the file to be read -- it must be an absolute path parameter 2: a configuration item, optional, and generally not required parameter 3: the callback function after the read is complete. This function has one parameter -- the error object */// Parameter 2 example:
const config = {
    root: __dirname + '/view/'.// Configure the template file and path
    headers: {                    // Configure the header
        'content-type':'text/html; charset=utf-8'}}Copy the code

Target: Display two pages in view directory, index.html and login. HTML

/ / target:
/ / the browser type http://127.0.0.1:3000/index, shows that the index. HTML
/ / the browser type http://127.0.0.1:3000/admin/login, shows the login. HTML//1. Load the express module
const express = require('express');
​
//2. Create a server
const app = express();
​
//3. Start the server
app.listen(3000.() = > {
    console.log('express-server is running... ');
});
​
const path = require('path');
​
//4. Listen for routes
app.get('/index'.(req, res) = > {
    /** * Function: reads the specified file content and returns it to the browser for display * This method is provided by express * Parameter 1: file path -- must be an absolute path * Parameter 2: configuration item, optional * Parameter 3: callback function after reading completion, with one parameter err */
    res.sendFile(path.join(__dirname, 'view'.'index.html'), (err) = > {
        if (err) {
            console.log(err);
        }
    })
})
​
app.get('/admin/login'.(req, res) = > {
    const obj = {
        root: path.join(__dirname, 'view'.'admin')}// Root is used to set the absolute path of the directory where the file is located.
    // With parameter 2, parameter 2 and parameter 1 are joined in an absolute path
    res.sendFile('login.html', obj, (err) = > {
        if (err) {
            console.log(err); }})})Copy the code

Open (hosted) static resources

Hosting CSS, JS, img and other files

app.use('/public', express.static('./public')); Urls that start with /public go to the public directory to read the corresponding file and return it to the browserCopy the code
// Target: load static resources (CSS, JS, img) when the page is displayed//1. Load the express module
const express = require('express');
​
//2. Create a server
const app = express();
​
//3. Start the server
app.listen(3000.() = > {
    console.log('express-server is running... ');
});
​
const path = require('path');
​
// Hosting/opening static resources
app.use('/public', express.static(path.join(__dirname, 'public')));
​
​
//4. Listen for browser requests
/ / when the url is: http://127.0.0.1:3000/list,
// Enter the following method to do the processing
app.get('/list'.(req, res) = > {
    res.sendFile(path.join(__dirname, 'view'.'list.html'), (err) = > {});
})
​
Copy the code

The next article will cover modularity and middleware for Node

Praise support, hand stay fragrance, and have glory yan, move your small hand to make a fortune yo, thank you for leaving your footprints.

Past excellent recommendation

Front ten thousand literal classics – basic

Front swastika area – advanced chapter

Let’s talk about two of the most common administrative tools used in front-end development

Talk about regular expressions

Hand touch hand take your liver Nodejs (1)

Obtain the file BLOB stream address to download the function

Hand touch hand take your liver NodeJS (2)

Git implements automatic push

Hand touch hand take your liver Nodejs (3)