🌐 Nodejs.cn

基本路由

_路由_是指确定应用如何响应客户端对特定端点的请求,该端点是一个 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:

  • appexpress 的一个实例。
  • METHOD 是一种 HTTP 请求方法,用小写字母表示。
  • PATH 是服务器上的一个路径。
  • HANDLER 是在路由匹配时执行的函数。

Caution

本教程假设已经创建了一个名为 appexpress 实例,并且服务器正在运行。如果你不熟悉创建应用和启动它,请参见 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 a 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.