點燈坊

失くすものさえない今が強くなるチャンスよ

使用 GET 讀取 Query String

Sam Xiao's Avatar 2021-10-26

若要以 Query String 傳遞資料,可透過 req.query 讀取。

Version

Express 4.17.1

req.query

import express from 'express'
import cors from 'cors'

let app = express ()
app.use (cors ())

app.get ('/api/articles', (req, res) => res.json ({
  pageSize: req.query.pageSize,
  pageNum: req.query.pageNum,
  articles: [
    {
      id: 1,
      title: 'Title 1',
      content: 'Content 1'
    },
    {
      id: 2,
      title: 'Title 2',
      content: 'Content 2'
    },
    {
      id: 3,
      title: 'Title 3',
      content: 'Content 3'
    }
  ]
}))
app.listen (8080, _ => console.log ('Node listen on port: 8080'))

第 7 行

app.get ('/api/articles', (req, res) => res.json ({
  pageSize: req.query.pageSize,
  pageNum: req.query.pageNum,
  articles: [
    {
      id: 1,
      title: 'Title 1',
      content: 'Content 1'
    },
    {
      id: 2,
      title: 'Title 2',
      content: 'Content 2'
    },
    {
      id: 3,
      title: 'Title 3',
      content: 'Content 3'
    }
  ]
}))

req.query 取得 query string。

query000

Conclusion

  • req.query 可簡單從 URL 讀取 query string

Reference

Express, req.query