配置 express 应用程序的中间件

配置 Express 应用程序的中间件,它们是处理 HTTP 请求体的两种常见方式。

1

express.urlencoded({extended: true}):

这是 Express 的内置中间件,用于解析 application/x-www-form-urlencoded 格式的请求体。 参数 {extended: true} 表示解析的对象可以包含任意类型的数据,并支持嵌套对象。 urlencoded 中间件将请求体解析为键值对的形式,并将其存储在 req.body 对象中。 例如,对于发送的表单数据:

<form method="POST" action="/submit">
    <input type="text" name="username" />
    <input type="text" name="password" />
    <button type="submit">Submit</button>
</form>

当表单提交时,express.urlencoded 将会解析 req.body 中的 username 和 password 字段。

2

express.json():

这是 Express 的内置中间件,用于解析 application/json 格式的请求体。 它会将请求体中的 JSON 字符串解析为 JavaScript 对象,并将其存储在 req.body 中。 例如,对于发送的 JSON 数据:

{
    "username": "john",
    "password": "secret"
}

express.json() 将会解析请求体,并使得 req.body 可以访问这些数据。

通过使用这两个中间件,你可以在 Express 应用程序中方便地处理不同格式的请求体数据,无论是来自表单提交还是通过 JSON 发送的数据。

Written on June 25, 2024