What is Express?

Express is a fast, open, minimalist Web development framework based on the Node.js platform. It provides a series of powerful features to help you create a variety of Web and mobile applications.

2. EXPRESS features

  • Web applications

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

  • API

Create powerful apis quickly and easily using a variety of HTTP utilities and middleware of your choice.

  • performance

Express provides streamlined basic Web application functionality without hiding the Node.js functionality you know and love.

Quick start

Install EXPRESS

Assuming you have Node installed, create a new project directory mkdir myExpress, CD myExpress NPM init Next install Express in myapp directory and save it to dependency list NPM install Express –save

The above commands will install the Express framework in the node_modules directory of the current directory, where the Express directory will be created automatically. There are several important modules that need to be installed with the Express framework:

  • body-parser 

Body-parser is an HTTP request body parser middleware for JSON, Raw, Text, and URL-encoded data. Bodyparser.json ()– Parse JSON format –bodyParser.raw()– parse binary format –bodyParser.text()– parse text format –bodyParser.urlencoded()– created Application/X-www-form-urlencoded,formData coded

  • cookie-parser 

This is a tool that parses cookies. Req. Cookies can be used to retrieve cookies that have been passed and turn them into objects.

  • multer 

Node.js middleware for processing form data encType =’multipart/form-data’ (setting the MIME encoding of the form).

npm install body-parser cookie-parser multer 

3.1 The first example Hello World

Create an Express application by creating an index.js configuration file. Express () is an entry function to express module exports

const express = require('express') const app = express() app.get('/', (req, res) => res.send('Hello World! ')) app.listen(3003, () => console.log('Example app listening on port 3003! '))Copy the code

3.2 Request and Response

Express applications use callback arguments: Request and Response objects to process request and response data.

app.get('/', function (req, res) { // --})
Copy the code

Request and Response objects:

3.2.1 the Request object

The Request object represents an HTTP request and contains attributes such as the request query string, parameters, content, and HTTP header. Common attributes are:

Req. app: When callback is an external file, use req.app to access the express instance req.baseUrl: Obtain the URL path req.body/req.cookies: Stale: determines whether the request is still fresh. Req. hostname/req. IP: obtains the hostname and IP address req.originalUrl: Path: specifies the request path. Protocol: specifies the protocol type. Req. query: specifies the query parameter string of the URL. Getting the currently matched route req.subdomains: Getting the subdomain req.accepts() : Req.acceptscharsets/req.acceptsencodings/req.acceptslanguages: returns the first acceptable character encoding of the specified character set req.get() : Gets the specified HTTP request header req.is() : Determines the MIME Type of the request header content-typeCopy the code

3.2.2 the Response object

A Response object represents an HTTP response, which is the HTTP response data sent to the client when a request is received. Common attributes are:

Res.append () : appends the specified HTTP header res.set() after res.append() resets the previously set header res.cookie(name, value [, option]) : Setting cookies opition: Domain/Expires/httpOnly/maxAge/path/secure/signed res.clearcookie () : Res.get () : returns the specified HTTP header res.json() : sends the JSON response res.jsonp() : sends the jsonp response res.location() : Set the Location HTTP header for the response without setting the status code or close response res.redirect() : Set the Location HTTP header for the response, and set the status code 302 res.render(view,[locals],callback) : Render a view and pass the rendered string to the callback. If an error occurs during rendering, next(Err) will be called automatically. Callback will be passed a possible error and the rendered page so that it will not be output automatically. Res.send () : sends HTTP response res.sendFile(path [, options] [, fn]) : sends a file in the specified path - Content-type res.set() : Res.status () : sets the HTTP status code res.type() : sets the CONTent-type MIME typeCopy the code

Write middleware for Express applications

Middleware functions are functions that can access request objects (REq), response objects (RES), and next functions in the application’s request-response cycle. The next function is a function in the Express router that, when called, executes the middleware after the current middleware.

The middleware features can perform the following tasks:

  • Execute any code.
  • Change the request and response objects.
  • End the request-response loop.
  • Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, then next() must be called to pass control to the next middleware function. Otherwise, the request will hang.

Start with version 4. X, Express no longer depends on Connect. Middleware functions previously included in Express are now in separate modules

Third-party middleware

4.1 the cookie – parser

  • Cookie Settings: Use Express’s built-in method res.cookie.
  • Cookie parsing: Use cookie-parser middleware.
var express = require('express'); var cookieParser = require('cookie-parser'); var app = express(); const cors = require('cors'); // app.use(cookieParser()); Use (cookieParser('123456')); // Unsigned // initialize the middleware, passing singed secret app.use(cookieParser('123456')); // Signature // use cORS cross-domain middleware // app.use(cors()); app.use(proxy) app.use(function (req, res, next) { console.log(req.cookies.username); console.log(req.signedCookies.username); Res. cookie('username', 'laney',{maxAge: 1000*60*60,signed: true}); next(); }); app.get('/info', (req, res) =>{ res.send('Hello World! '); console.log(req.cookies.username); // Second access, output laney}); app.listen(3000);Copy the code

The server may need to retrieve cookies, and the server needs to explicitly specify the Access-Control-allow-credentials field to tell the browser that it is ok to send cookies

Also, the developer must turn on the withCredentials attribute in the AJAX request.

res.setHeader(‘Access-Control-Allow-Credentials’, ‘true’); True Allows cookies to be carried false does not carry cookies

Note that access-Control-allow-Origin cannot be set to an asterisk if the server requires the browser to send cookies, and must specify an explicit domain name that matches the requested web page. At the same time, cookies still follow the same origin policy, only the Cookie set with the server domain name will be uploaded, cookies of other domain names will not be uploaded, and (cross-domain) the document. Cookie in the original web page code can not read the Cookie under the server domain name.

Function proxy(req, res,next){function proxy(req, res,next){ http://192.168.1.29:8080 is the address res.setheader (' access-Control-allow-origin ', 'http://192.168.1.29:8080'); // res.setHeader('Access-Control-Allow-Origin', '*'); // Allow any source. If the server asks the browser to send a Cookie, This cannot be set to * res.setHeader(' access-Control-allow-methods ', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); Res.setheader (' access-control-allow-methods ', '*'); res.setHeader('Access-Control-Allow-Headers', 'X-Token,Content-Type') // res.setHeader('Access-Control-Allow-Headers', The '*'); // Allow any type res.setHeader(' access-Control-allow-credentials ', 'true'); next(); // Next is a recursive call}Copy the code

Is axios used?

Axios is not allowed in the default setting cookies, so if used, need you to separate a jumpstart global Settings axios. Defaults. The withCredentials = true; // Make Ajax carry cookies in the entry page Settings to be used globally.

axios.defaults.withCredentials = true; // True allows cookies, false does notCopy the code

Is cookie enabled during node background startup? res.header(‘Access-Control-Allow-Credentials’, ‘true’);

Function: Easy to operate the cookie value in the client.

  1. The cookie-parser third-party cookie operation module is installed
yarn add cookie-parser

Copy the code
  1. The introduction of
const cookieParser = require('cookie-parser'); app.use(cookieParser('123456')); // Using cookie middleware, pass signature 123456 for encryptionCopy the code
  1. To set a cookie, you need to set a signed signature
res.cookies('key','value',option)
Copy the code

The option requirement is to be in JSON format: there are the following options

  • Domain: the domain name. Set whether subdomain names (secondary domain names) can access cookies. For example: domain:’. Primary domain ‘name=value: Key/ value pair, you can set the Key/ value to save, note that the name cannot be the same as the name of other attributes
  • Expires: Expires in seconds. The Cookie expires after a certain time, for example, Expires =Wednesday, 09-NOV-99 23:12:40 GMT
  • MaxAge: indicates the maximum expiration time (milliseconds)
  • Secure: When secure is true, cookies are invalid in HTTP but valid in HTTPS
  • Path: indicates the route affected by the cookie, for example, path=/. If the path does not match, the browser does not send the Cookie
  • HttpOnly: The default value is false. The recommended value is true. The client cannot read cookie information through document.cookie, which prevents XSS attacks
  • Signed: indicates whether to sign (encrypt) the cookie. If set to true, the cookie will be signed, so that res.signedcookies will be used to access it. Unsigned access with res.cookies
  • A tampered signature cookie is rejected by the server and the cookie value is reset to its original value
Res. Cookies (' cart '{items: [1, 2, 3]}, {maxAge: 10000 * 4, signed: true, httpOnly: true}); res.cookie('username', "laney", { maxAge: 10000*2,signed:true});Copy the code
  1. To get a cookie
// signedCookies: console.log(req.signedcookies); console.log(req.signedCookies.username); // Unsigned cookie console.log(req.cookie.username);Copy the code

4.2 Functions of cookie Signature

It is mainly for security reasons to prevent cookies from being tampered with and enhance security

Expand based on the previous example. Suppose the web site uses the Nick cookie to identify who is currently logged in. In the previous example, in the cookie of the login user, the value of username is as follows :(after decode)

S: laney. UVofnk6k + 9 mhqpdplqeofjm8b5oa6mppny9d + mG9rD0 at this point, attempts to modify the cookie value, to achieve the goal of forged identity. For example, change it to xiaoming:

. S: xiaoming uVofnk6k + 9 mhqpdplqeofjm8b5oa6mppny9d + mG9rD0 when a website, receipt of a request for signing the cookie parsing, found the signature verification does not pass. Therefore, it can be determined that the cookie is forged.

It is bad design to determine which user is logged in only by the value of the cookie username. Although it is difficult to forge a signed cookie when the secret key is unknown. However, if the user name is the same, the signature is the same. In this case, it’s actually very easy to fake.

In addition, the open source component’s algorithm is public, so the security of the secret key is key to ensure that the secret key is not leaked.

Five, routing,

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI(or path) and a particular HTTP request method (GET, POST, and so on). Each route can have one or more handler functions that are executed when a route is matched.

app.METHOD(PATH, HANDLER)

Copy the code

Note: App is an instance of Express. METHOD is the HTTP request METHOD (lowercase), such as POST, GET,put, and so on. PATH is the PATH on the server. HANDLER is a function that is executed when a route is matched.

app.get('/ab? cd', function (req, res) { res.send('ab? cd') })Copy the code
app.get('/users/:userId/books/:bookId', function (req, res) {
  res.send(req.params)
})
Copy the code

5.1 Route Handlers

You can provide multiple callback functions that behave like middleware to handle requests. The only exception is that these callbacks may call next(‘route’) to bypass the remaining route callbacks. You can use this mechanism to impose preconditions on routes and then pass control to subsequent routes if there is no reason to continue with the current route.

app.get('/example/b', function (req, res, next) { console.log('the response will be sent by the next function ... ') next() }, function (req, res) { res.send('Hello from B! ')})Copy the code

5.2 Response Header Methods — Response Methods

The methods on the response object (RES) in the following table can send a response to the client and terminate the request-response cycle. If these methods are not invoked from the route handler, the client request will hang.

methods describe
res.download() The file prompted to download.
res.end() End the response.
res.json() Send a JSON response
res.jsonp() Send a JSONP-enabled JSON response.
res.redirect() Redirect request
res.render() Render view template
res.send() Send various types of responses
res.sendFile() Send files as streams
res.sendStatus() Sets the response status code and sends its string representation as the response body

5.3 app. The route ()

You can use app.route() to create linkable route handlers for routing paths. Because paths are specified in a single location, it helps to create modular routes, as does reducing redundancy and spelling errors.

app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Add a book')
  })
  .put(function (req, res) {
    res.send('Update the book')
  })

Copy the code

5.4 Express. Router can be mounted

Use Express to create modular mountable route handlers. A router instance is a complete middleware and routing system; For this reason, it is often referred to as a “mini-application”. The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main application. Create a router file named birds.js in your app directory with the following contents:

var express = require('express'); var router = express.Router(); Router. use(function timeLog (req, res, next) {console.log('Time: ', date.now ()) next()}) router.get('/home', function (req) Res) {res.send('Birds home page')}) // router. Get ('/about', function (req) res) { res.send('About birds') }) module.exports = router;Copy the code

Then load the router module in the APP

var birds = require('./birds')
// ...
app.use('/birds', birds)
Copy the code

The application will now be able to handle /birds/home and /birds/ About requests, as well as invoke route-specific timeLog middleware functionality.

Use Express to host static files

Express provides built-in middleware express.static to set static files such as images, CSS, JavaScript, etc. You can use express.static middleware to set static file paths. For example, if you put images, CSS, and JavaScript files in a public directory, you could write:

app.use(express.static('public'));
Copy the code

Now you can access all files in the public directory:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
Copy the code

Express looks for files in static directories, so the name of the directory where the static files are stored does not appear in the URL. If you want to use multiple static resource directories, call the Express. static middleware function multiple times:

app.use(express.static('public'))
app.use(express.static('files'))
Copy the code

Create a virtual path prefix (where the path does not actually exist in the file system) for the files provided by Express. Static function to specify a mount path for the static directory, as shown below:

app.use('/static', express.static('public'))
Copy the code

You can now access files in the public directory with the /static prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
Copy the code

Use (‘/static’, express.static(path.join(__dirname, ‘public’))) app.use(‘/static’, express.static(path.join(__dirname, ‘public’)))

Express application generator

You can quickly create an application skeleton by applying the generator tool Express-Generator. Express-generator includes the Express command line utility. You can run the following command to partially install:

Installation: YARN add Express-generator

Of course, you can also choose global installation, but the configuration is a bit more difficult

Win10 安装express and express-generator win10安装express and express-generator win10安装express and express-generator win10安装express and express-generator win10安装express and express-generator win10安装express and express-generator win10安装express and express-generator win10安装express and express-generator win10安装express 'Express' is not an internal or external command, nor is it a runnable program or batch file modified, Must remember to restart the console service environment variable configuration reference: https://blog.csdn.net/m0_37750720/article/details/82937463Copy the code

When you use NPM to install some global software packages, you can run the NPM root -g command to query the installation location. By default, the packages are saved in the following locations:

The -h argument lists all available command-line arguments: NPX express -h Creates the project using the express command

NPX express --view= EJS myApp NPX express --view= EJS -- CSS =less myAppCopy the code

The command creates an Express application named MyApp. The application will be created in the myApp directory under the current directory and set to use the EJS View Engine.

Then install all dependencies:

cd myapp
npm install
node bin/www
Copy the code

If you want to listen to configuration files in real time, you can use nodemon bin/ WWW. The nodemon must be installed globally

Then open http://localhost:3000/ in your browser to see the application.

Applications created with generators typically have the following directory structure: ├─ ├─ WWW ├─ package.json └─ ├─ WWW ├─ package.json │ ├─ WWW ├─ package.json │ ├─ WWW ├─ package.json │ ├─ WWW ├─ package.json ├─ public.html CSS Image JS │ ├─ public.css Image JS │ ├─ public.css Image JS │ ├─ │ ├─ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ index.js │ ├─ ├─ index. ├─ ├─ index. ├─ ├─ index Layout.pug node_modules: // All installed dependencies are in this folder

Creating an application through Express application Generator is just one of many ways. You can either leave it out or modify it to suit your needs.

Start the project through PM2, install:

npm install pm2 -g

Pm2 start app.js Note: pm2 is started in the background and can also operate other commands

7.1 Using the Template Engine of Express

The template engine allows you to use static template files in your application. At run time, the template engine replaces the variables in the template file with the actual values and converts the template to an HTML file that is sent to the client. This approach makes it easier to design HTML pages.

Some popular template engines that use Express are Pug, Mustache, and EJS. The Express application generator uses Jade as the default, but it also supports several other features.

npm install ejs–save app.set(‘views’, ‘.views’); Set (‘ View engine’, ejs) // Register the template engine

Write a simplified version of Express

1. The experience express

const express = require('./common/myexpress.js');
const app = express();
app.get('/',(req,res) => {
    res.end('Hello world')
})
app.get('/users',(req,res) => {
    res.end(JSON.stringify({name:'abcooooo'}))
})
app.get('/list',(req,res) => {
    res.end(JSON.stringify({name:'list'}))
})
app.listen(3200 , () => {
    console.log('Example listen at 3200')
})

Copy the code

2. Implement myexpress

const http = require('http'); const url = require('url'); let routers = []; class Application { get(path,hander){ routers.push({ path, method:'get', hander }); } listen(){ const server = http.createServer(function(req,res){ const {pathname} = url.parse(req.url,true); const {method,headers} = req; console.log(method); // At the routers, go to pathName to find the callback. Then run the var tet = Routers. Find (v=>{return v.path == pathName && req.method.tolowercase ()== v.mode}) tet && tet.hander(req,res); }) // Add the listen method to the Application prototype and execute the corresponding Hander server.listen(... arguments) // server.listen(3200,() => { // console.log('Example listen at 3200') // }) } } module.exports = function(){  return new Application(); }Copy the code