表格发送空对象

问题描述 投票:0回答:1

我正在尝试创建一个具有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发送数据时,它可以正常工作并将对象保存到数据库中]

node.js typescript express
1个回答
1
投票

[sending data via an HTML form时,应考虑请求的标题。 在这种情况下,相关的标题为:

Content-Type: application/x-www-form-urlencoded

这意味着您在服务器端收到的请求正文将不是JSON格式(因此将被解析为一个空对象)。

因此,为了像您一样使用请求的正文,您首先需要解析它。幸运的是,您可以使用一些外部库将其转换为JSON格式,如here所述。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.