Express.js or node.js req.body undefined
#Express.js or node.js req.body undefined
We have many usecase to get undefine value that is coming from HTML Form Tag.
<form class="form text-center" method="post" action="/api/Search">
<input name="name" class="form-control-sm" type="text" id="search">
</form>
There is multiple solutions to consider in this situation :-
Ensure that you have the body parser middleware configured in your Express application. Body parser is responsible for parsing incoming request bodies, including JSON.
In app.js you can add this middleware :-
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json
Based on header type and Correct Content-Type Header should be used.
response.setHeader('Content-Type', 'text/html');
we can mention below option in content type :-
Change method type to get to post or Post and excute your application.
for example :-
router.post('/api/Search', async (req, res) => {
//logic
}
router.get('/api/Search', async (req, res) => {
//logic
}
You should be able to fix the issue of req.body not being defined in your Express.js application by taking care of these typical problems. If the problem continues, you could want to verify that the data is being transmitted appropriately by looking at your front end code.