Table of contents
2.1. Configure the GET request under the route and return the corresponding content.
2.2. Configure the POST request under the route and return the corresponding content.
2.3. Configure the PUT request under the route and return the corresponding content.
2.4. Configure the DELETE request under the root route and return the corresponding content.
2.5. Configure the PAATCH request under the root route and return the corresponding content.
1. Application Builder
Use the App Builder tool express-generator
to quickly create app skeletons.
You can npx
run the app generator with the command (available in Node.js 8.2.0).
npx express-generator
For earlier Node versions, install app-generator as a global npm package, then start it:
npm install -g express-generator
express
After the execution is complete, it looks like this:
The default page template is jade
express -h
command options with options:
$ express -h
Usage: express [options] [dir]
Options:
--version 版本编号
-e, --ejs 增加ejs引擎支持
--pug 增加pug引擎支持
--hbs 增加handlebars 引擎支持
-H, --hogan 增加hogan.js引擎支持
-v, --view <engine> 增加视图引擎支持(dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
--no-view 使用静态html而不是视图引擎
-c, --css <engine> 增加样式表引擎支持(less|stylus|compass|sass) (defaults to plain css)
--git 增加 .gitignore
-f, --force 强制非空目录
-h, --help 输出使用信息
Then install dependencies:
cd myapp
npm install
In the command window, run npm start to start the project.
npm start
The default interface is 3000, enter http://localhost:3000/ in the browser, the page is as follows:
2. Basic routing
Routing refers to determining how an application responds to a client's request for a specific endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, etc.).
Each route can have one or more handler functions, which are executed when the route is matched.
A route definition takes the following structure:
app.METHOD(PATH, HANDLER)
app
isexpress
an instance of .METHOD
is the lowercase HTTP request method
.PATH
is the path on the server.HANDLER
is the function executed when a route is matched.
Corresponding routing method:
- ACL
- BIND
- CHECKOUT
- CONNECT
- COPY
- DELETE
- GET
- HEAD
- LINK
- LOCK
- M-SEARCH
- MERGE
- MKACTIVITY
- MKCALENDAR
- MKCOL
- MOVE
- NOTIFY
- OPTIONS
- PATCH
- POST
- PROPFIND
- PROPPATCH
- PURGE
- PUT
- REBIND
- REPORT
- SEARCH
- SOURCE
- SUBSCRIBE
- TRACE
- UNBIND
- UNLINK
- UNLOCK
- UNSUBSCRIBE
- acl
- bind
- checkout
- connect
- copy
- delete
- get
- head
- link
- lock
- m-search
- merge
- mkactivity
- mkcalendar
- mkcol
- move
- notify
- options
- patch
- post
- propfind
- proppatch
- purge
- put
- rebind
- report
- search
- source
- subscribe
- trace
- unbind
- unlink
- unlock
- unsubscribe
The following is a simple way to test each route with several commonly used methods:
2.1. Configure the GET request under the route and return the corresponding content.
app.get('/', (req, res) => {
res.send("这是一个GET请求,返回的结果!")
})
2.2. Configure the POST request under the route and return the corresponding content.
app.post('/', (req, res) => {
res.send("这是一个POST请求,返回的结果!")
})
2.3. Configure the PUT request under the route and return the corresponding content.
app.put('/', (req, res) => {
res.send("这是一个PUT请求,返回的结果!")
})
2.4. Configure the DELETE request under the root route and return the corresponding content.
app.delete('/', function(req, res, next) {
res.send("这是一个DELETE请求,返回的结果!");
});
2.5. Configure the PAATCH request under the root route and return the corresponding content.
app.patch('/', function(req, res, next) {
res.send("这是一个PATCCH请求,返回的结果!");
});
3. Static files
Like our common static files, such as images, css, javascript, html, font files, etc., Express provides the express.static() built-in middleware function for processing. Based on serve-static
The syntax structure is as follows:
express.static(root, [options])
Note: For better performance, use a reverse proxy to improve the performance of your server's static resources.
The root parameter specifies the root directory of static resources.
The following table describes the properties of the options object.
Attributes | describe | type | Defaults |
---|---|---|---|
dotfiles |
Determines how dot files (files or directories beginning with a dot ".") are handled. | String | “ignore” |
etag |
Enable or disable etag generation Note: Weak ETags are always sent. express.static |
Boolean | true |
extensions |
Set file extension fallback: If a file is not found, search for a file with the specified extension and provide the first file found. example:.['html', 'htm'] |
Mixed | false |
fallthrough |
Let client errors fall through as unhandled requests, otherwise forward client errors. | Boolean | true |
immutable |
Enable or disable directives in response headers. If enabled, this option should also be specified to enable caching. This directive will prevent supported clients from making conditional requests during the lifetime of the option to check whether the file has changed.immutable Cache-Control maxAge immutable maxAge |
Boolean | false |
index |
Send the specified directory index file. Set to to disable directory indexing. | Mixed | “index.html” |
lastModified |
Set the header to the last modified date of the file on the operating system.Last-Modified |
Boolean | true |
maxAge |
Sets the cache-control header's maxAge property in milliseconds or a string in ms format . |
Number | 0 |
redirect |
When the pathname is a directory, redirect to follow "/" at the end. | Boolean | true |
setHeaders |
Function for setting HTTP headers to serve with a file. | Function |
public
For example, the pictures, CSS files, and JavaScript files in the directory can be opened to the public through the following code :
app.use(express.static('public'))
Create an html file in the public directory, for example: test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
H5 页面
</body>
</html>
Start the service, visit http://localhost:3000/test.html
If you want to use multiple static resource directories, please call express.static
the middleware function multiple times:
app.use(express.static('public'))
app.use(express.static('files'))
When accessing static resource files, express.static
the middleware function will look for the required files according to the order in which the directories are added.
Currently we can also add a prefix to the directory of static files, for example: static
app.use('/static', express.static('public'))
Then the access address becomes http://localhost:3000/static/test.html