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:其中:

This tutorial assumes that an instance of express named app is created and the server is running. 本教程假设已创建名为appexpress实例,并且服务器正在运行。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.有关布线的更多详细信息,请参阅布线指南

Previous: Express application generatorExpress应用程序生成器     Next: Serving static files in Express在Express中提供静态文件