node.js - 表单发送空对象
问题描述
我正在尝试使用 express、typescript 和 ejs 作为视图引擎创建一个 REST,用于在前端显示数据。我在 ejs 中创建了一个表单:
<form action="/app" method="post">
<div class="input-group mb-3">
<label>
<input type="text" name="title" placeholder="Title" class="form-control">
</label>
</div>
<div class="form-group">
<label>
<input name="url" placeholder="Url" class="form-control">
</label>
</div>
<div class="form-group">
<label>
<textarea type="text" name="description" placeholder="Description"
class="form-control"></textarea>
</label>
</div>
<div class="form-group">
<button class="btn btn-success btn-block" type="submit">
Send
</button>
</div>
</form>
这个表单向路由发送一个 POST 请求/app
,这是应该执行的函数:
public async saveLink(req: Request, res: Response): Promise<void> {
console.log(req.body)
const {title, url, description} = req.body;
const newLink = new LinkModel({title, url, description});
await newLink.save();
res.json({status: res.status, data: newLink});
}
在控制台中,函数打印:
{}
(node:22256) UnhandledPromiseRejectionWarning: ValidationError: LinkModel validation failed: title: Path `title` is required., url: Path `url` is required.
at model.Document.invalidate (C:\Users\pablo\Desktop\Trabajo\Programación\Yt-video-keeper\node_modules\mongoose\lib\document.js:2574:32)
at C:\Users\pablo\Desktop\Trabajo\Programación\Yt-video-keeper\node_modules\mongoose\lib\document.js:2394:17
at C:\Users\pablo\Desktop\Trabajo\Programación\Yt-video-keeper\node_modules\mongoose\lib\schematype.js:1181:9
at processTicksAndRejections (internal/process/task_queues.js:79:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:22256) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:22256) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
如您所见,它将 req.body 打印为空对象,因此不会接收数据。但是当我通过 POSTMAN 发送数据时,它工作正常并将对象保存到数据库
解决方案
通过HTML 表单发送数据时,您应该关注请求的标头。
在这种情况下,相关的标题是:
Content-Type: application/x-www-form-urlencoded
这意味着您在服务器端收到的请求正文不会是 JSON 格式(因此会被解析为空对象)。
因此,为了像您一样使用请求的主体,您首先需要解析它。
幸运的是,您可以使用一些将其转换为 JSON 格式的外部库,如此处所述。
推荐阅读
- php - 从 PHP 调用简单的 Golang 可执行文件失败并出现 exec:“zip”:在 $PATH 中找不到可执行文件
- apache-nifi - 使用 Apache Nifi 在 CSV 中转换日期格式
- reactjs - React - 状态变量不反映变化
- regex - 在 Flutter/Dart 中用于简单数学计算的输入格式化程序正则表达式
- visual-studio - Visual Studio - 将每个新项目的“将警告视为错误”更改为全部
- python - 为什么这些循环输出不同?
- javascript - 如何在 p5.js 中为 loadimage() 使用本地服务器?
- c# - 如何避免在多个地方使用 BuildServiceProvider 方法?
- python-3.x - 谷歌表格日期到熊猫日期时间意外偏移
- python - 计算一个值的实例并忽略 Pandas 中的连续重复