基本路由

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

路由定義的結構如下:

app.METHOD(PATH, HANDLER)

Where:

  • appexpress 的實例。
  • METHOD is an HTTP request method, in lowercase.
  • PATH 是伺服器上的路徑。
  • HANDLER 是當路由相符時要執行的函數。

This tutorial assumes that an instance of express named app is created and the server is running. 這項指導教學假設已建立名稱為 appexpress 實例,且伺服器正在執行。如果您不熟悉如何建立和啟動應用程式,請參閱 Hello world 範例

下列範例說明如何定義簡單的路由。

首頁中以 Hello World! 回應。

app.get('/', (req, res) => {
 res.send('Hello World!')
})

Respond to a POST request on the root route (/), the application’s home page:

app.post('/', (req, res) => {
 res.send('Got a POST request')
})

/user 路由發出 PUT 要求時的回應:

app.put('/user', (req, res) => {
 res.send('Got a PUT request at /user')
})

/user 路由發出 DELETE 要求時的回應:

app.delete('/user', (req, res) => {
 res.send('Got a DELETE request at /user')
})

如需路由的詳細資料,請參閱路由手冊

Edit this page

AltStyle によって変換されたページ (->オリジナル) /