I'm trying to create a REST with express, typescript and ejs as view engine for showing the data in the frontend. I have created a form in 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>
And this form send a POST request to the route /app
and this is the function that should be executed then:
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});
}
An in the console, the function prints:
{}
(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.
As you can see, its prints req.body as a empty object, so the data is not recived. But when I send the data throught POSTMAN, it works fine and save the object to the database