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('/', function (req, res) {
  res.send('Hello World!')
})

Respond to POST request on the root route (/), the application’s home page:响应根路由(/)上的POST请求,应用程序主页:

app.post('/', function (req, res) {
  res.send('Got a POST request')
})

Respond to a PUT request to the /user route:响应对/user路由的PUT请求:

app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})

Respond to a DELETE request to the /user route:响应对/user路由的删除请求:

app.delete('/user', function (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中提供静态文件