mirror of
https://github.com/expressjs/expressjs.com.git
synced 2026-02-22 03:51:33 +00:00
Co-authored-by: Crowdin Bot <support+bot@crowdin.com> Co-authored-by: bjohansebas <103585995+bjohansebas@users.noreply.github.com>
1.9 KiB
1.9 KiB
layout, title, description, menu, order, redirect_from
| layout | title | description | menu | order | redirect_from |
|---|---|---|---|---|---|
| page | Express 基本路由 | Learn the fundamentals of routing in Express.js applications, including how to define routes, handle HTTP methods, and create route handlers for your web server. | starter | 4 |
基本路由
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:
app是express的實例。METHODis 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.
這項指導教學假設已建立名稱為 `app` 的 `express` 實例,且伺服器正在執行。如果您不熟悉如何建立和啟動應用程式,請參閱 [Hello world 範例](/{{ page.lang }}/starter/hello-world.html)。
下列範例說明如何定義簡單的路由。
首頁中以 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')
})
如需路由的詳細資料,請參閱[路由手冊](/{{ page.lang }}/guide/routing.html)。