這個翻譯StrongLoop / IBM提供.

相對於英文版說明文件,本文件可能已不合時宜。如需最新的更新,請參閱英文版說明文件

基本路由

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:

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!')
})

對根路由 (/)(應用程式的首頁)發出 POST 要求時的回應:

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')
})

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

Previous: Express application generator     Next: Serving static files in Express

Edit this page