static是Express自帶的中間件,主要用於處理客戶端對於靜態文件的請求,用法以下:html
示例代碼:/lesson02/server.jsgit
server.use(express.static('./static/'))
複製代碼
打開http://localhost:8080/index.html,便可看到頁面顯示。github
這段代碼的含義以下:express
server.use(express.static('./static/'))
server.get('/reg', (req, res, next) => {
res.send({
error: 0,
msg: '請求成功'
})
})
複製代碼
此時中間件會直接將first文件返回到客戶端,而/first接口將沒法被訪問。npm
在Express中,接口的數據須要分開處理:json
Express已經自動處理了GET請求的數據,只須要經過req.query就能夠獲取:bash
server.get('/reg', (req, res, next) => {
console.log(req.query)
res.send({
error: 0,
data: req.query
})
})
複製代碼
POST數據能夠運行命令npm install body-parser
,安裝中間件body-parser進行處理。app
接下來分別以表單提交和Fetch提交數據,講解一下body-parser的使用。less
新建一個/lesson02/static/index.html
文件,建立表單提交和Fetch請求提交代碼async
示例代碼:/lesson02/static/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h3>表單提交</h3>
<form action="/login" method="POST">
用戶:<input type="text" name="username" id="username"><br />
密碼:<input type="text" name="password" id="password"><br />
<input type="submit" value="表單登陸">
</form>
<h3>Fetch提交</h3>
<input type="button" value="GET註冊" id="reg">
<input type="button" value="POST登陸" id="login">
<script>
// 註冊
document.querySelector('#reg').addEventListener('click', async function () {
const response = await fetch(`/reg?username=${document.querySelector('#username').value}&password=${document.querySelector('#password').value}`)
const result = await response.json()
console.log(result)
alert(result.msg)
})
// 登陸
document.querySelector('#login').addEventListener('click', async function () {
const response = await fetch(`/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: document.querySelector('#username').value,
password: document.querySelector('#password').value
})
})
const result = await response.json()
console.log(result)
alert(result.msg)
})
</script>
</body>
</html>
複製代碼
使用bodyParser.urlencoded處理表單提交數據
示例代碼:/lesson02/server.js
// 處理表單提交,對應請求頭application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({
extended: false
}))
複製代碼
使用bodyParser.json處理Fetch請求數據
示例代碼:/lesson02/server.js
// 處理fetch請求,對應請求頭application/json
server.use(bodyParser.json())
複製代碼
接收處理後的數據
處理後的數據會被保存在req.body屬性中,能夠在路由的配置中獲取數據。
路由的配置必須卸載body-parser中間件以後。
示例代碼:/lesson02/server.js
server.post('/login', (req, res, next) => {
console.log(req.body)
res.send({
error: 0,
data: req.body,
msg: '登錄成功'
})
})
複製代碼