I have a code where I get data using the post method, but such an error occurs, what's the problem? todos.js
router.post('/create', async (req, res) => {
const todo = new Todo({
title: req.body.title
})
todo.save();
create.hbs
<form action="/create" method="POST">
<h2>Create todo</h2>
<div >
<input type="text" name="title">
<label>Todo title</label>
</div>
<button type="submit" >Create</button>
</form>
index.js
const express = require('express');
const mongoose = require('mongoose');
const expressHandlebars = require('express-handlebars');
const PORT = process.env.PORT || 3000;
const todoRoutes = require('./routes/todos')
app.use(todoRoutes);
app.use(express.urlencoded({
extended:true
}));
CodePudding user response:
It appears that req.body
is undefined
. That would mean that you don't have any middleware that is reading and parsing the body of the POST request and placing the results into req.body
.
Since this is a regular form post, it will using the content-type application/x-www-form-urlencoded
which can be parsed with the middleware express.urlencoded()
.
I see you have that middleware, but it is AFTER your route so it won't run before your route gets called. Route handlers and middleware run in the order they are declared. So, change this:
app.use(todoRoutes);
app.use(express.urlencoded({
extended:true
}));
to this:
app.use(express.urlencoded({
extended:true
}));
app.use(todoRoutes);
Also, keep in mind that you should be doing server-side validation of everything that the client sends. In this case, you might be getting a request that doesn't have a title or has an empty title. Your server should be checking for that and return a non 200 http status if you are getting bad data from the client. Do not just assume that all the correct data has arrived with the incoming request. Verify the data before using it. This is the brute force dirty work that gives you a reliable server.
CodePudding user response:
My guess is that you have your app.use()
in the incorrect order. Expressjs executes these in order.
Update your index.js to
const express = require('express');
const mongoose = require('mongoose');
const expressHandlebars = require('express-handlebars');
const PORT = process.env.PORT || 3000;
const todoRoutes = require('./routes/todos')
const app = express()
app.use(express.urlencoded({
extended:true
}));
app.use(todoRoutes);