introduce
- Express is a third-party module used toquickly build servers similar to jquery and DOM
- Express is abased on Node.js platform, fast, open and minimalistweb development Frame.
- express retains the basic API of the http module. When using express, you can also use the http API.
- express also encapsulates some additional new methods, allowing us to build servers more conveniently
Express official website
Express Chinese documentation (unofficial)< /span>
Express GitHub repository
node framework
node-http model ==⇒ express frame ==⇒ koa =⇒ egg.js
Install
npm i express
New method of express packaging
- express
express.static()
– Open static resourcesexpress.urlencoded()
– Get POST request body
- app
app.get()
– Handle client’s GET requestapp.post()
– Handle client’s POST requestapp.use()
– Set application level configuration
- req
req.body
– Get POST request bodyreq.params
– Get GET request dynamic parametersreq.query
– Get GET request parameters (get query string parameters)
- res
res.sendFile(文件的绝对路径)
– Read the file and respond with the resultres.set({name, value})
– Set response headersres.status(200)
– Set response status coderes.send(字符串或对象)
– response resultsres.json(对象)
– Response results in JSON formatres.jsonp()
– Response results in JSONP format
Please note that in express we can still use methods from the http module.
Simple requests and complex requests
simple request
If it meets the following conditions, it is asimple request:
- The request method can only be: GET, HEAD, POST
- And the value of Content-Type is limited to
- text-plain
- multipart/form-data
- application/x-www-form-urlencoded
Complex request
Features:Send two requests
A preflight request will be sent firstOPTIONS
IfOPTIONS
allows cross-domain header information, the browser will send a second request
Constructing a web server using Express
nodemon
Start the service.
step
- Load express module
- Create express server
- Start the server
- Listen to browser requests and process them
// 1. 导入express模块
const express = require('express')
// 2. 创建服务器
const app = express()
// 3. 启动服务器
app.listen(3000, function () {
console.log('服务器启动成功')
})
// express 处理用户请求
// app.get() 用于处理用户的get请求
// app.post() 用于处理用户的post请求
app.get('/index',(req,res) => {
res.send('你好,新世界')
})
app.get('/login', (req,res) => {
res.send('<h1>哈哈</h1>')
})
// 更多的是返回一个数据(express自动把这个对象转化为JSON )
app.get('/user', (req,res) => {
res.send({
name: 'zs',
age: 18,
gender: '女'
})
})
Implement get interface
Interface server:
Return data (JSON data) based on the user's request
Implement a simple get interface
const express = require('express')
const app = express()
app.listen(3000, () => {
console.log('服务器启动成功了')
})
app.get('/login', (req, res) => {
// 允许该接口跨域访问 CROS
res.setHeader('Access-Control-Allow-Origin', '*') // *表示都可以跨域访问
res.send({
code: 200,
message: '成功'
})
})
Get query string
What is a query string?
These following the url address:
Usereq.query
Get query string
- interface
const express = require('express')
const app = express()
app.listen(3000, () => {
console.log('服务器启动成功了')
})
app.get('/login', (req, res) => {
// 允许该接口跨域访问
res.setHeader('Access-Control-Allow-Origin', '*') // *表示都可以跨域访问
console.log(req.query)
const {
username, password} = req.query
if(username === 'admin' && password === '123456') {
res.send({
code: 200,
message: '成功'
})
} else {
res.send({
code: 400,
message: '用户名或密码错误'
})
}
})
The query string obtained:
- page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" placeholder="请输入用户名" class="username">
<br>
<input type="text" placeholder="请输入密 码" class="pwd">
<br>
<button>登录</button>
<script src="node_modules/axios/dist/axios.js"></script>
<script>
document.querySelector('button').onclick = async function () {
const username = document.querySelector('.username').value
const password = document.querySelector('.pwd').value
const res = await axios({
method: 'get',
url: 'http://localhost:3000/login',
params: {
username,
password
}
})
console.log(res)
}
</script>
</body>
</html>
Get dynamic parameters
url/:id/:name/:age
: The following are called dynamic parameters
Usereq.params
to obtain dynamic parameters
app.get('/getUser/:id', (req, res) => {
// 允许该接口跨域访问
res.setHeader('Access-Control-Allow-Origin', '*')
console.log(req.params)
res.send({
id: req.params.id,
name: 'zs',
age: 10
})
})
Interface style
The more popular one at present is REST style, which is a simple interface style.
Performance: id is directly spliced into the url, that is, using dynamic parameters
Implement post request
Note: Since the post request's Content-Type
is application/json
, it is a complex request.
Send post request steps
- Handle all options requests
app.options('*', (req, res) => {
// 允许CORS跨域的域名
res.setHeader('Access-Control-Allow-Origin', '*')
// 允许CORS跨域的请求方式,默认只有GET,POST
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE')
// 允许CORS跨域请求的请求头
res.setHeader('Access-Control-Allow-Headers', 'content-type')
res.send(null)
})
- Send post request
app.post('/login', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*')
res.send({
code: 200,
message: '登陆成功'
})
})
- If you want to get the request body of the post request
- use
req.body
- Must use a built-in middleware
**express.json()
- use
app.use(express.json())
...
...
app.post('/login', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*')
console.log(req.body)
res.send({
code: 200,
message: '登陆成功'
})
})
The server receives different types of request bodies and uses them in different ways.
- urlencoded —>
app.use(express.urlencoded({extended: false}));
- application/json —>
app.use(express.json());
– no demo - form-data —> The server uses third-party module processing (
multer
)
middleware
The intermediate processing link in the special business processing process
-
Middleware is a function, usually written before the request
-
There are three basic parameters
- req requests related objects
- res response related objects
- next function, must call next middleware to pass down
const express = require('express') const app = express() // app.use(中间件) // 所有的请求之前都会调用中间件 const middle = function (req, res, next) { console.log('我是中间件') // 处理完一定要记得调用next next() } app.use(middle) app.listen(3000, () => { console.log('服务器启动了') }) app.get('/login', (req, res) => { res.send('登录') }) app.get('/user', (req, res) => { res.send('用户') }) app.get('/index', (req, res) => { res.send('首页') })
Use middleware to solve cross-domain problems
Declare a middlewareAllowCrossDomain
const express = require('express')
const app = express()
// app.use(中间件) // 所有的请求之前都会调用中间件
const AllowCrossDomain = function (req, res, next) {
// 允许CORS跨域的域名
res.setHeader('Access-Control-Allow-Origin', '*')
// 允许CORS跨域的请求方式,默认只有GET,POST
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE')
// 允许CORS跨域请求的请求头
res.setHeader('Access-Control-Allow-Headers', 'content-type')
// 处理完一定要记得调用next
next()
}
app.use(AllowCrossDomain)
app.listen(3000, () => {
console.log('服务器启动了')
})
app.post('/login', (req, res) => {
res.send({
code: 200,
message: '登陆成功'
})
})
app.get('/user', (req, res) => {
res.send('用户')
})
app.get('/index', (req, res) => {
res.send('首页')
})
express built-in middleware
- static
Static resources
// img是一个文件夹
// 直接把img作为公共的静态资源目录
app.use(express.static('img'))
- urlencoded
- deal with
application/x-www-form-urlencoded
- Hang the request body on req.body
- json
- deal with
application/json
- Hang the request body on req.body
- deal with
Usually 2 and 3 are used at the same time
// 处理json数据
app.use(express.json())
// 处理form-urlencoded数据
app.use(express.urlencoded({
extended: false}))