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