¥Basic routing
路由是指确定应用如何响应客户端对特定端点的请求,该端点是 URI(或路径)和特定的 HTTP 请求方法(GET、POST 等)。
¥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.
路由定义采用以下结构:
¥Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
其中:
¥Where:
app
是 express
的一个实例。
¥app
is an instance of express
.
METHOD
是小写的 HTTP 请求方法。
¥METHOD
is an HTTP request method, in lowercase.
PATH
是服务器上的路径。
¥PATH
is a path on the server.
HANDLER
是路由匹配时执行的函数。
¥HANDLER
is the function executed when the route is matched.
本教程假设已创建名为 app
的 express
实例并且服务器正在运行。如果你不熟悉创建应用并启动它,请参阅 Hello World 示例。
¥This tutorial assumes that an instance of express
named app
is created and the server is running. If you are not familiar with creating an app and starting it, see the Hello world example.
以下示例说明了定义简单路由。
¥The following examples illustrate defining simple routes.
在首页响应 Hello World!
:
¥Respond with Hello World!
on the homepage:
app.get('/', (req, res) => {
res.send('Hello World!')
})
响应根路由(/
)上的 POST 请求,应用的主页:
¥Respond to POST request on the root route (/
), the application’s home page:
app.post('/', (req, res) => {
res.send('Got a POST request')
})
响应对 /user
路由的 PUT 请求:
¥Respond to a PUT request to the /user
route:
app.put('/user', (req, res) => {
res.send('Got a PUT request at /user')
})
响应对 /user
路由的 DELETE 请求:
¥Respond to a DELETE request to the /user
route:
app.delete('/user', (req, res) => {
res.send('Got a DELETE request at /user')
})
有关路由的更多详细信息,请参阅 路由指南。
¥For more details about routing, see the routing guide.