Express教程02:使用中間件處理靜態文件和數據請求

閱讀更多系列文章請訪問我的GitHub博客,示例代碼請訪問這裏

static中間件

static是Express自帶的中間件,主要用於處理客戶端對於靜態文件的請求,用法如下:

示例代碼:/lesson02/server.js

server.use(express.static('./static/'))

打開http://localhost:8080/index.html,即可看到頁面顯示。

這段代碼的含義如下:

  1. server.use方法使用中間件。
  2. express.static中間件方法,告知靜態文件存放地址爲./static/,若有請求靜態文件,則自動根據請求地址返回相應的文件。
  3. express.static中間件建議放在接口處理之後。
    否則如果有請求文件名與接口同名,如有一個名爲first的文件存在,而中間件的處理又在/first接口之前,如下:
server.use(express.static('./static/'))

server.get('/reg', (req, res, next) => {
  res.send({
    error: 0,
    msg: '請求成功'
  })
})

此時中間件會直接將first文件返回到客戶端,而/first接口將無法被訪問。

接口數據處理

在Express中,接口的數據需要分開處理:

GET請求數據

Express已經自動處理了GET請求的數據,只需要通過req.query就可以獲取:

server.get('/reg', (req, res, next) => {
  console.log(req.query)
  res.send({
    error: 0,
    data: req.query
  })
})

POST請求數據

POST數據可以運行命令npm install body-parser,安裝中間件body-parser進行處理。

接下來分別以表單提交和Fetch提交數據,講解一下body-parser的使用。

  1. 新建一個/lesson02/static/index.html文件,創建表單提交和Fetch請求提交代碼

    示例代碼:/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>
    
  2. 使用bodyParser.urlencoded處理表單提交數據

    示例代碼:/lesson02/server.js

    // 處理表單提交,對應請求頭application/x-www-form-urlencoded
    server.use(bodyParser.urlencoded({
      extended: false
    }))
    
  3. 使用bodyParser.json處理Fetch請求數據

    示例代碼:/lesson02/server.js

    // 處理fetch請求,對應請求頭application/json
    server.use(bodyParser.json())
    
  4. 接收處理後的數據

    處理後的數據會被保存在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: '登陸成功'
      })
    })
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章