Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the express route in node.js

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "what is express routing in node.js". In the operation of practical cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. The concept of routin

1.1 what is routing

In a broad sense, routing is a mapping relationship.

In real life

Button 1-> business query button 2-> Mobile Phone Top-Up Service button 3-> business processing button 4-> password service and shutdown button 5-> home broadband button 6-> phone traffic button 8-> group business button 0-> manual service here, routing is the mapping between buttons and services.

1.2 routing in nodejs

The route in nodejs is actually the mapping between the url address and the response function, and a url address responds to a html page.

Is to extract the business of a path matching relationship into a separate js file.

2. Express

2.1 introduction to Express

A fast, open and minimalist web development framework based on Node.js platform

Express official website (http://expressjs.com/)

Express Chinese Network (http://expressjs.com.cn/)

1. The function of Express is similar to Node.js 's built-in http module, which is specifically used to create Web servers.

2. The essence of Express: it is a third-party package on npm that provides a convenient way to quickly create a Web server.

Learn more about express

Think about it: can you create a Web server without Express?

Answer: yes, just use the native http module provided by Node.js.

Think about it: both Yu and he Shengliang (with the http built-in module, why still use Express)?

Answer: the http built-in module is very complex to use, and the development efficiency is low; Express is further encapsulated based on the built-in http module, which can greatly improve the development efficiency.

Consider: what is the relationship between http built-in modules and Express?

Answer: similar to the relationship between Web API and jQuery in browsers. The latter is further encapsulated based on the former.

2.2 basic steps for use

Installation: npm i express

/ / Import expressvar express = require ('express'); / / create an express instance, that is, create an express server var app = express (); / / start the server app.listen (3000, function () {console.log (' server started')})

Listen for get requests

Through the app.get () method, you can listen to the client's GET request in the following syntax format:

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-wu5WkyIV-1639963661922) (images3/image-20200529231606651.png)]

Listen for post requests

Through the app.post () method, you can listen to the client's POST request in the following syntax format:

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-wzB8FFER-1639963661923) (images3/image-20200529231710830.png)]

Respond to the content to the client

Through the res.send () method, you can send the processed content to the client:

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-Iiifw7XV-1639963661924) (images3/image-20200529231837638.png)]

2.3 detailed explanation of req attributes

Get the parameters of the get request

Through the req.query object, you can get the parameters that the client sends to the server through GET:

For example: http://127.0.0.1:3000/index?id=10&name=tom&age=20

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-WUoF7b2h-1639963661925) (images3/image-20200529231928577.png)]

The name functions as req.query to get the parameters passed by the Get request, getting an object req.body to get the data passed by the Post request, and getting an object. You need to register a middleware req.params to get the routing parameters in the Get request, and get an object.

Example: jd.com/32342545365

App.get ('/ product/:id') req.get (key) gets the Value corresponding to the specified Key in the request header

Get the parameters of the post request

You can get the parameters of the post request through req.body, but you need to cooperate with body-parser middleware

You no longer need to use req.on ('data',chunk= > {}) req.on (' end', () = > {})

If there is no such middleware, the default is undefined.

/ / the latest express version no longer requires download support for body-parse. You can write app.use (express.urlencoded ({extended: true})) app.post ('/ index', (req,res) = > {console.log (req.body);}) as follows.

2.4 detailed explanation of res attributes

/ / send () sends data to the client, and automatically sets Content-Typeres.send () / / to respond to the browser client with appropriate response header / / send the file to the browser And automatically set Content-Type// according to the file suffix name Note: the file path must be the absolute path res.sendFile (path.join (_ _ dirname, 'index.html')) / / set the response header res.set (' Content-Type', 'text/plain') res.set ({' Content-Type': 'text/plain') 'cute':' fangfang'}) / / the redirect res.redirect ('/ index') method responds to the data sent to the client browser by res.send () and comes with a response header

When the send method responds to the above object data to the browser, it is equivalent to internally calling JSON.stringify () res.sendFile (path) to respond to a page res.redirect () redirected to the browser with its own status code res.set (key,value) custom response header res.status () to set the response status code.

2.5 express routing processing

Basic use

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-D3rId34r-1639963661925) (images3/image-20200529233016669.png)]

App.get (path, callback)

App.post (path, callback)

App.use (path, callback) plays a more important role in dealing with middleware.

Note: any request address that begins with path can be processed by use.

Note: you can handle any type of request

Note: the path parameter can be omitted. The default value is: /

/ / all can match any submission method get and post can app.all ('*', (req,res) = > {/ / make a more friendly interface response to the browser res.send ('page is not finished, please wait.'))

Route matching process

Whenever a request arrives at the server, it needs to be matched by a route, and the corresponding handler function will not be called until the match is successful.

When matching, the match will be carried out in the order of routes. If the request type and the URL of the request are matched at the same time, the Express will transfer the request to the corresponding function function for processing.

Attention points for route matching:

① matches in the order defined.

The corresponding handler will not be called until the ② request type and the URL of the request are matched successfully.

Globally mount rout

The easiest way to use routing in Express is to mount the route to app. The sample code is as follows

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-pdjsILgz-1639963661927) (images3/image-20200529233254606.png)]

2.6 Modular routing

To facilitate modular management of routes, Express does not recommend that routes be mounted directly to the app, but rather that routes be extracted into separate modules.

The steps to extract the route into a separate module are as follows:

① creates the .js file router.js corresponding to the routing module

② calls the express.Router () function to create a routing object

③ mounts a specific route to the routing object

④ uses module.exports to share routing objects

⑤ uses the app.use () function to register the routing module

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-3fEDx0H3-1639963661928) (images3/image-20200529233324503.png)]

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-QAUKjV4x-1639963661931) (images3/image-20200529233330060.png)]

2.7 static resource processing

Basic use

Express provides a very useful function, called express.static (), through which we can easily create a static resource server. For example, we can open access to images, CSS files and * * JavaScript * * files in the public directory by using the following code:

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-C1BTBqzr-1639963661933) (images3/image-20200529232407154.png)]

Now you can access all the files in the public directory: http://localhost:3000/images/bg.jpghttp://localhost:3000/css/style.csshttp://localhost:3000/js/login.js Note: Express looks for files in the specified static directory and provides the access path to the resources. Therefore, the name of the directory where the static files are stored does not appear in URL.

Host multiple resource directories

If you want to host multiple static resource directories, call the express.static () function multiple times:

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-Px6ZUuaQ-1639963661934) (images3/image-20200529232555610.png)]

The above settings should be noted: those static resource paths in the html page must not appear public.

When accessing a static resource file, the express.static () function looks for the desired file based on the order in which the directory is added.

Mount path prefix

If you want to mount the path prefix before the managed static resource access path, you can use the following ways:

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-e13liOYs-1639963661934) (images3/image-20200529232626696.png)]

Now you can access the files in the public directory with the / public prefix address: http://localhost:3000/public/images/kitten.jpghttp://localhost:3000/public/css/style.csshttp://localhost:3000/public/js/app.js

2.8express middleware

What is middleware?

Middleware (Middleware) is actually a function, especially the intermediate processing part of a business process.

It is divided into global middleware and routing middleware.

There are two kinds of middleware, one is global middleware and the other is routing middleware.

Examples in real life

This intermediate treatment link of sewage treatment can be called middleware.

Middleware in express

When a request arrives at the server of Express, multiple middleware can be called successively to preprocess the request.

Basic use

The middleware of Express is essentially a function processing function. The format of Express middleware is as follows:

Const mw = function (req, res, next) {next ()} app.use (mw)

Note: the next parameter must be included in the formal parameter list of the middleware function. The route handling function contains only req and res.

The role of the next function: the next function is the key to the continuous call of multiple middleware, which indicates that the transfer relationship is transferred to the next middleware or route.

The role of middleware

Share the same req and res among multiple middleware. Based on this feature, we can uniformly add custom properties or methods for req or res objects in the upstream middleware for downstream middleware or routing.

Define multiple middleware

You can use app.use () to define multiple global middleware in succession. After the client request arrives at the server, it will be called in the order defined by the middleware. The sample code is as follows:

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-s5pYXD4F-1639963661937) (images3/image-20200529233901695.png)]

Express built-in middleware

Since Express version 4.16.0, Express has built in three commonly used middleware, which has greatly improved the development efficiency and experience of Express projects:

① express.static quickly hosts built-in middleware for static resources, such as HTML files, pictures, CSS styles, etc. (not compatible)

② express.json parses request body data in JSON format (compatible, only available in version 4.16.0 +)

③ express.urlencoded parses request body data in URL-encoded format (compatible, only available in version 4.16.0 +)

[external link image transfer failed. The origin server may have hotlink protection mechanism. It is recommended to save the image and upload it directly (img-WJaSINca-1639963661937) (images3/image-20200529234155137.png)]

3.EJS template

3.1 ejs introduction

Ejs is an efficient javascript template engine designed to separate user pages from business data.

Simply put, using the ejs template engine can help us quickly render the data to the corresponding location on the page, similar to the art-template template.

3.2 use of ejs

1. download

Npm i ejs

two。 Configure template engine

App.set ('view engine','ejs')

3. Directory where the configuration template is stored

App.set ('views','./views') / / can be omitted by default

4. Create a static page in the template file views folder under the views directory at this time you should modify the suffix. ejs

5. Render data using a template

Res.render ('index',obj) / / the first parameter is the page to be rendered. Write the name directly without the suffix / / the second parameter indicates the object to be rendered, usually an object

3.3 data rendering

Write business logic

Output data at a location

No escape output

This is the end of the content of "what is express routing in node.js". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report