In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to use express". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use express" can help you solve the problem.
Introduction to express
Express is a fast, open and minimalist Web development framework based on Node.js platform. Set up web server
The essence of Express: it is a third-party package on npm that provides a convenient way to quickly create a Web server.
Using the Express development framework, you can easily and quickly create servers for Web websites or servers with API interfaces.
Official website: https://www.expressjs.com.cn/
Easy to use
Download and install:
Npm init-ynpm i express-S
Steps to use:
Import package
Create a server
Process the request
Listening port
Const express = require ('express') const app = express () app.get (routing, callback) / / get is the request method app.listen (port number) routing method
The request method also supports:
Get-query request-condition is in the address bar
Post-add request-data in the request body
Put-modify request-condition in address bar-data in request body
Delete-Delete request-condition is in the address bar
Each verb method is used to process the corresponding request. However, there is one exception:
App.all () / / can be used to handle any request method
Although the all method can handle any request, use it as little or as little as possible.
Debugging with postman
Routing path
perfect match
/ app.get ('/', function (req, res) {res.send ('root');}); / / request app.get to match / about path (' / about', function (req, res) {res.send ('about');}); / / request app.get to match / random.text path (' / random.text', function (req, res) {res.send ('random.text');})
Not an exact match
/ match acd and abcdapp.get ('/ ab?cd', function (req, res) {res.send ('ab?cd');}); / match app.get such as abcd, abbcd, abbbcd (' / ab+cd', function (req, res) {res.send ('ab+cd');}); / match app.get such as abcd, abxcd, abRABDOMcd, ab123cd (' / ab*cd', function (req, res) {res.send ('ab*cd');}) / / match / abe and / abcdeapp.get ('/ ab (cd)? eBay, function (req, res) {res.send ('ab (cd)? e');})
The characters?, +, * and () are subsets of regular expressions,-and. Interpreted literally in a string-based path.
Regular matching:
/ / match any path with an in it: app.get (/ a res.send, function (req, res) {res.send ('/ a res.send');}); / / match butterfly, dragonfly, but not butterflyman, dragonfly man, etc. App.get (/. * fly$/, function (req, res) {res.send ('/. * fly$/');}); route processing multiple times
Use a callback function to handle routing:
App.get ('/ example/a', function (req, res) {res.send ('Hello from Aids');})
Multiple processes:
App.get ('/ example/b', function (req, res, next) {console.log ('after this is processed will be handed over to the next function'); next ();}, function (req, res) {res.send ('Hello from financing');})
Use an array of callback functions to handle routes:
Var cb0 = function (req, res, next) {console.log ('CB0') next ()} var cb1 = function (req, res, next) {console.log (' CB1') next ()} var cb2 = function (req, res) {res.send ('Hello from cargo')} app.get ('/ example/c', [cb0, cb1, cb2])
Use a mix of functions and function arrays to handle routing:
Var cb0 = function (req, res, next) {console.log ('CB0') next ()} var cb1 = function (req, res, next) {console.log (' CB1') next ()} app.get ('/ example/d', [cb0, cb1], function (req, res, next) {console.log ('response will be sent by the next function...') Next ()}, function (req, res) {res.send ('Hello from dating')}) response method res.download () / / prompt to download the file. Res.end () / / finalizes the response processing flow. Res.json () / / sends a response in JSON format. Res.jsonp () / / sends a response in JSON format that supports JSONP. Res.redirect () / / redirect the request. Res.render () / / render view template. Res.send () / / sends various types of responses. Res.sendFile () / / sends the file as an octet stream. Res.sendStatus () / / sets the response status code and sends it as a string as part of the response body.
Download example:
/ / response to download-res.download (downloaded source file, file name after download, callback function) res.download (". / test.html", 'b.htmldownload error = > {if (err) {console.log ("download failed");} else {console.log ("download successful");}})
Json example:
/ / json data to the client / / res.json (data in json format) let obj = {name: "Zhang San", age:12, wife: "Cuihua", children: ['A Da','An er', 'Xiao Ming']} res.json (obj)
Jsonp example:
/ / respond to the jsonp request initiated by the client, responding to json data / / res.jsonp (data in json format) let obj = {name: "Zhang San", age:12, wife: "Cuihua", children: ['A Da','An er', 'Xiao Ming']} res.jsonp (obj)
Redirect example:
/ / res.redirect () is used to jump the route-/ a, in fact, the route / b can handle him. In the route processing of / a, the request can be handed over to the route / b to process res.redirect ('/ index') app.get ('/ index', (req,res) = > {let data = fs.readFileSync ('. / test.html') res.end (data)}).
Send example:
/ / res.send ()-used to give the client response string-if the string is a tag, it can be parsed into html-automatically set the data type and encode let html = `This is an h3 tag `/ / res.end will not automatically set the data type, nor will it set the encoding / / res.end (html) res.send (html)
SendFile example:
/ / res.sendFile () is used to give the client a response file res.sendFile (_ _ dirname +'/ test.html')
SendStatus example:
/ / sendStatus automatically sets the response status code and describes the corresponding response status to the client res.sendStatus / / response not foundres.sendStatus / / response ok request object attribute req.url / / request path-if any? Pass parameters, this path will also take the parameter req.method / / request method req.path / / request path-if any? Pass parameters. This path does not contain parameters req.protocol / / protocol req.params / / to get the parameters of the get request-parameters for dynamic routing-parameters of restful style-what is finally obtained is the object, the key of the object, that is, the name specified by the path req.query / / get the parameters of the get request-pass parameters for traditional forms-use? Parameter-finally gets the object static resource hosting
Express provides a very useful method called express.static (), which makes it very convenient to create a static web resource server:
App.use (express.static ('public')) / / app.use () means to use (middleware) / / now you can access all files in the public directory / / such as public/aa.jpg files, you can use: http://xxxx/images/aa.jpg
Express also supports the creation of a virtual file prefix for static resource files (which does not actually exist in the file system). You can use the express.static function to specify a virtual static directory, like this:
Meaning of use of prefixes:
It can confuse others and prevent them from guessing the directory structure of our server to a certain extent.
It can help us better organize and manage static resources.
App.use ('/ static', express.static ('public'))
The "/" before the prefix must be added, otherwise it will be wrong. [404]
Now you can use / static as a prefix to load the files in the public folder:
Http://localhost:3000/static/images/kitten.jpghttp://localhost:3000/static/css/style.csshttp://localhost:3000/static/js/app.jshttp://localhost:3000/static/images/bg.pnghttp://localhost:3000/static/hello.html
The app.use () method is generally written before the specific route snooping.
Each application can have multiple static directories.
Introduction to app.use (express.static ('public')) app.use (express.static (' uploads')) app.use (express.static ('files')) routing
Routing in life, such as when making a service call, what kind of processing it can handle by pressing a number is similar to the mapping relationship between keys and services. In Express, routing refers to the mapping between the request (address) initiated by the client and the server-side processing method (function).
The route in express consists of three parts, namely, the request type (method), the request uri (address), and the corresponding handler function.
When a client request arrives at the server, the routing rules are matched first, and only after the matching is successful, the corresponding processing function is called. 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 for processing.
App. (uri, (req,res) = > {}) / / use method is not a request type method, but it is placed in the same location as the request method routing modularization
Meaning: the routing rules that could have been written in a file are split into several routing files (js file, a js file is a module).
As the name implies, routing is modularized and managed in terms of modules (js files). Birds of a feather flock together.
Core idea: disassemble as long as it can't, decoupling, high cohesion, low coupling).
When developing a project, if all routing rules are mounted into the entry file, programming and maintenance become more difficult. Therefore, for the modular management function of routing, express creates a routing modular handler through the express.Router () method, which can separate different business requirements into different modules, thus facilitating code maintenance and project expansion.
Steps:
Specify the request at the beginning of the path, using app.use (path beginning, processing module)
The request path at the beginning of app.use ('/ admin',adminRouter) / admin is handed over to the adminRouter module to handle the request path at the beginning of app.use ('/ front',frontRouter) / front, and to the frontRouter module for processing
This module is not defined. Define this module.
Let {adminRouter} = require ('. / admin/admin') let {frontRouter} = require ('. / front/front')
The imported file has not been defined yet. Create the file
Const express = require ('express') const adminRouter = express.Router () / / create routing object / / process the remaining requests through the routing object adminRouter.get (' / goods', (req,res) = > {res.send ('this is the goods page of the admin module')}) / / Export module module.exports = {adminRouter}
At this point, we have two more scenarios to process the request:
App.get/post/use...
Express.Router (). Get/post...
App.route (path) .get/post ()
The abbreviation of multiple requests using different request methods for the same request path:
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');}); middleware
Middleware (middleware) can be understood as the intermediate processing part of a business process and as an intermediate filter.
Classification of middleware
Middleware can be classified into the following categories:
Built-in middleware, that is, express itself comes with no need for npm installation
Express.static ()
Third-party middleware
Middleware, which is not officially built into Express, but developed by a third party, is called third-party middleware. Third-party middleware can be installed and configured through npm in the project, so as to improve the development efficiency of the project. For example, body-parser (parsing post data) this middleware can easily help us to get the data submitted by post.
Custom middleware, written by developers themselves (the essence of middleware is actually a function)
From the perspective of usage, middleware can be divided into:
Application-level middleware (middleware bound to app instances through app.get/post/use, etc.)
App. Request method (address, [middleware … ,] callback function)
App. Request method (address, middleware 1, intermediate 2, intermediate 3... ,] callback function)
App.use (middleware)
Use middleware globally (all routes are in effect)
Local use of middleware (current route takes effect)
Routing-level middleware (bound to middleware on express.Router ())
Router.use (middleware)
Router. Request method (address, [middleware … ,] callback function)
Its usage is no different from application-level middleware, except that one is tied to the app instance and the other to the router.
Built-in middleware
Express provides useful built-in middleware, such as a static resource management middleware, which can help us quickly build a static resource server:
App.use ('prefix', express.static ('managed directory address'))
In express, in addition to the built-in express.static () middleware, there are also two other commonly used middleware:
Express.json ()
Examples of use:
/ / with this middleware, we can send json data from the client to the server, and the json data will be placed on the body attribute of the request object req app.use (express.json ()) app.post ('/ p1marker, (req,res) = > {/ / express.json middleware allows data to be hung on the body attribute of req console.log (req.body); res.send ('this p1 request is ended')}))
First of all, it must be a post request, and then there must be data, but the data cannot be data like the previous x-www-form-urlencoded, it must be raw data.
Then the content-type of the request header must be application/json
Function: to receive data submitted in json format
Compatibility issues: express > = 4.16.0
App.use (express.json ())
After receiving the data, it will mount the object form of the data to the body attribute of the req request object.
Express.urlencoded ()
Purpose: processing post form data
Compatibility issues: express > = 4.16.0
App.use (express.urlencoded ({extended: false}))
After receiving the data, it will mount the object form of the data to the body attribute of the req request object.
Be careful,
The two commonly used built-in middleware mentioned later have compatibility problems.
The above two middleware say that the data will be processed and hung on the req.body, but in fact, there will not be the problem of coverage.
Case: use json and urlencoded middleware to receive json data and form post data, and send them through postman
Custom middleware
The essence of custom middleware is to define a function to handle requests, but in addition to request and response parameters, this function must also include a next parameter, which allows the middleware to allow the process to execute down until the response is sent to the client in the matching route. You can also pass down the middleware data by adding properties to the request object.
Function mfn (req,res,next) {/ / The logical flow / / middleware that you need to define must finally execute this function, otherwise the program cannot go down to next ()}
Note: all middleware share a req and res with the final route throughout the request link
Case: based on the above common features, customize a middleware to receive form data submitted by post (meaning: is there a compatibility problem with the built-in middleware)
Third-party middleware
In express, it allows us to use third-party middleware to process data. For example, third-party middleware can be used to receive post data.
Take using body-parser middleware to receive post data as an example, the steps are as follows:
Install tripartite middleware body-parser
Npm I-S body-parser
Import body-parser in the application file
Call app.use (body.urlencoded ({extended: false})) through middleware
Get data in post through req.body in matching routes
Express's built-in express.urlencoded middleware is further packaged based on body-parser, a third-party middleware. But the built-in ones have version compatibility problems, so general projects choose to install and use third-party middleware.
When in use, the syntax of the body- parser library is very similar to the syntax of express's built-in express.urlencoded middleware seen earlier, because the built-in middleware is implemented based on body-parser.
Other third-party middleware: http-proxy-middleware/cors/cookie-session …
Exception handling middleware
* * function: * * is specially used to catch the exception errors occurred in the whole project, so as to prevent the problem of project abnormal collapse (friendly display exception).
* * format: * * among the function parameters of error-level middleware, there must be four formal parameters, which are (err,req,res,next)
Q: what is the purpose of the extra err parameters?
Answer: it contains the error information, and the err.message attribute contains the error text information, which can be output to the user in the middleware.
App.get ('/', (req,res) = > {throw new Error ('fatal error occurred inside the server!') Res.send ('Welcome to my homepage')}) app.use ((err,req,res,next) = > {console.log (' error:'+ err.message) res.send ('error') + err.message)})
* * case: * * A path is required (the file corresponding to the route may not exist), read the contents of the file, and output it to the user
Note: for error-level middleware to work, it must be written after all routes, regardless of whether it is before app.listen or not.
404 middleware
* * function: * * used to process the request response of 404
/ / suppose the route is defined, but / 12345 is requested during the actual request, and then 404app.post ("/ 1234", (req, res, next) = > {res.send ('your request succeeded')}) / / the middleware also needs to be written last (regardless of the order of the exception middleware, just make sure it is available after all routing methods) app.use ((req,res,next) = > {/ / output 404 error res.status (404). Send ('404') / / specify the 404 status code first and then output the error message})
404 error middleware is also required to declare use after all normal request routes, not in front of the route, otherwise it will cause the following routes to be 404 errors.
* * Note: * * error-level middleware must be registered after all routes. As for 404 middleware and exception middleware, it doesn't matter who comes first.
Template page: page: https://404.life/
Other modules cookie
The principle of cookie is to open up a browser to store the data in the http request. After the first save, as long as the current browser is still used in the next request, the data in the browser space can be accessed.
Cookie is carried between the response header and the request header as a key-value pair.
Characteristics of cookie:
Domain name limit. Cookie set under the current domain name can only be used under the current domain name.
Timeliness, cookie will not be permanently stored in the browser, with a certain period of validity
Quantity limit. Under normal circumstances, each domain name cannot exceed 50 cookie.
Space limit, cookie can only store 4kb
Data type limit, only strings can be stored in cookie
Npm I cookie-parser-S
Use:
/ / Import const cookieParser = require ('cookie-parser') / / Middleware app.use (cookieParser ()); / / request headers get req.headers.cookie / / get all cookie// response headers set res.cookie (key, value, {maxAge: validity-millisecond}) / / set cookiesession
Cookie is stored in the browser, so the security is not high, so some important data can not be stored in cookie, and the storage space of cookie is limited, so there is session.
Session is on the storage server side, and session needs to rely on the cookie,session data store to store a sessionid in the cookie. This sessionid will have a mapping relationship with the server side. If the sessionid is tampered with, it will not be hidden from the server side, so the security factor is higher. And the validity period of session is relatively short. It usually takes about 20 minutes, and if the browser does not interact with the server within 20 minutes, the server will delete the session data.
Npm I cookie-session-S
Use:
/ / Import: const session = require ('cookie-session') / / session configure session ({name: "sessionId", secret: "asdfasdfqwer", / / key for sessioinId encryption, fill in maxAge:20*60*1000 / / 20 minutes}) / / set sessionreq.session [key] = value / / get sessionreq.session [key] encrypt npm i bcryptjs-S
Use:
Var bcrypt = require ('bcryptjs'); / / encrypted ciphertext = bcryptjs.hashSync (plaintext [, number]); / / number, salt will be generated using the specified number of rounds and used. Recommend 10Universe / verify bcryptjs.compareSync (plaintext, ciphertext); / / return falsejwtnpm install jsonwebtoken by returning true and failure
Use:
/ / encryption generates tokenvar jwt = require ('jsonwebtoken'); var token = jwt.sign (encrypted object, salt); / / verify jwt.verify (token, salt, function (err, decoded) {/ / decoded is decrypted object}); file upload npm i multer-S
Use:
Var multer = require ('multer') var upload = multer ({dest: path.join (_ _ dirname,'public','image')}) / / specify the uploaded file path app.post (' / profile', upload.single ('upload form name value'), function (req, res) Next) {/ / req.file is the uploaded file information-you can get the file name, path, suffix-the stitching path is stored in mongodb}) mysqlnpm i mysql-S
Use:
/ / Import const mysql = require ("mysql"); / / create connection object const db = mysql.createConnection ({host: "localhost", user: "root", password: "root", database: "test"}); / / connection db.connect (err= > {if (err) {console.log ("connection failed, error:" + err); return;} console.log ("connection successful");}) / / execute statement db.query (", (err,result) = > {if (err) {console.log (" failure, error: "+ err); return;} console.log (" success "); console.log (result);}); npm I svg-captcha-S
Use:
Const svgCaptcha = require ('svg-captcha') / / create CAPTCHA let captcha = svgCaptcha.create (); / / captcha is an object containing the data key and text key, text is the character on the CAPTCHA, and data is a svg tag that can be displayed directly as a picture email to send npm install nodemailer-- save
Use:
Const nodemailer = require ('nodemailer') / / 1. Create the sender const transport = nodemailer.createTransport ({/ / you need to send the stmp domain name and password for email and some other information / / need you to copy it and find the downloaded nodemailer third-party package / / nodemailer-> lib-> well-known-> services.json "host": "smtp.qq.com", "port": 465, "secure": true) / / prove your identity auth: {/ / user name of the sender's mailbox user: 'mailbox number', / / stmp allow password pass: 'authorization code'}) / / 2. Send email transport.sendMail ({/ / send from: 'sender mailbox' from that mailbox, / / where to, you can write a string, mailbox, or an array, write many mailboxes to: ['receiving mailbox', 'receiving mailbox'], / / email title subject: 'title' / / the hypertext content of this email html: `Hello: the verification code is 2345. Please use it within 3 minutes.
-
The text content of this email / / text:''}, function (err, data) {if (err) return console.log (err) console.log ('email sent successfully') console.log (data)}) template engine introduction
In a web application, if you only use server-side code to write client-side html code, the front and back ends are not separated, then it will cause a lot of work, and the written code will be more difficult to read and maintain. If you only use the client-side static HTML file, then the back-end logic will be more difficult to integrate into the client-side HTML code. In order to facilitate maintenance, and make the back-end logic better integrate into the front-end HTML code, and at the same time easy to maintain, many third-party developers have developed a variety of Nodejs template engines, of which the more commonly used are Jade/Pug, Ejs and art-template template engines.
Objective: to make the back-end logic better integrate into the front-end HTML code and be easy to maintain.
Art-template is a simple, ultra-fast template engine.
Development mode:
Traditional development model:
The front-end code and back-end code are written together.
Mixed together, but this kind of file has a requirement, and the file is usually in the back-end language file to write the back-end logic-- in this case, it is particularly unfriendly to us front-end engineers, because we front-end engineers are responsible for html pages, but we can't write back-end logic in html pages. If we put html pages in back-end files, we need to learn back-end languages.
At this point, the template engine appears-the template engine actually allows us to write back-end logic-loop / judgment in the html page.
There are many kinds of template engines: jade/ejs/art-tamplate …
The template engine can eventually write logic in html, which is the equivalent of a syntax mixed between the front and back of our code. Why is it finally recognized by browsers? Because our template engine needs to compile-html code before the browser can recognize it.
Front and back end separate development mode:
Html wrote it alone.
The back-end interface is written by another person.
Docking between the two sides, using interface documentation
All the data on html is requested by ajax and displayed on the page through dom operation.
Template engine rendering speed test:
Characteristics
Performance close to the limit of JavaScript rendering (DOM operation) (fast)
Debug-friendly: syntax and runtime error logs are accurate to the lines of the template; breakpoints on template files are supported (Webpack Loader)
Support for Express, Koa, Webpack
Support for template inheritance (layout) and subtemplates (introduction of inclusion)
Browser version only 6KB size
Use
Download and install:
# install npm I-S art-template express-art-template
Configuration:
/ / template engine configuration / / specify the art-template template and specify the module suffix .htmlapp.engine ('html', require (' express-art-template')); / / specify the template view path app.set ('views', path.join (_ _ dirname,' views')); / / omit the suffix name of the specified module file (optional, the suffix that can be omitted when rendering) app.set ('view engine',' html')
Art-template supports * * standard syntax and original syntax * *. The standard grammar can make the template easy to read and write, while the original grammar has a strong ability of logical expression. The standard syntax supports basic template syntax as well as basic JavaScript expressions; the original syntax supports arbitrary JavaScript statements, just like Ejs.
Use art-template to display a view (html file)
Put the view under the views directory (subdirectories are allowed)
The way to write code and display the view is `res.redner (path to the file)
App.get ('/', (req, res) = > {/ / output view res.render ('404.html')})
The control layer returns data (assign variables to the view in the js control layer)
App.get (uri, (req,res) = > {res.render (template, {username: 'Zhang San', age: 25, gender: 'female', hobby: ['basketball', 'table tennis', 'badminton']}) template syntax
Variable output:
{{username}}
By default, the above output method does not allow content with HTML tags to be parsed by the browser, but will only be output as is. If you need to give the HTML tag to the browser, output the data in the following way:
{{@ username}}
Condition judgment:
{{if condition}} … {{else if condition}} … {{/ if}}... ...
Loop:
{{each loop data}} {{$index}} {{$value}} {{/ each}} {{each loop data val key}} {{key}} {{val}} {/ each}}
If you use the default key, the name of the value (index,value), then the $before it must be written! Be sure to write!
If you use a custom key and the name of the value, the preceding $must not be written! Can't write!
Template Import:
{{include 'was introduced into the file path'}}
If it is under the current path, be sure to write. /, if you don't write, start looking at the root of the disk.
The file suffix of include defaults to .art. If not, do not omit it.
It is best not to have html, head and body tags in the subtemplate (otherwise it is prone to style errors)
Template inheritance:
Inherited template:
{{block 'title'}} My Site {{/ block}} {{block' content'}} {{/ block}}
Subtemplates that need to be inherited:
{{extend'. / layout.html'}} {{block 'title'}} Home Page {{/ block}} {{block' content'}}
This is just an awesome page.
{{/ block}} this is the end of the introduction on "how to use express". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.