Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js & express: req.body undefined

I'm currently designing a simple browser application utilizing express. I'm trying to extract the value a user selects in a drop down menu. I gave each option an individual value as well and have declared the method of the form as /post. but when I try which value they selected by going into the req.body, the value is undefined.

I recognize that the problem could lie with the body parser from browsing through similar questions (Example, Example1) but the solutions from these questions don't keep req.body from being undefined.

Here's my code for the app construction

const app = express()
app.use(express.static(__dirname, ''));
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/public/views');
app.use(express.urlencoded());
app.set('view engine', 'html');
const server = http.createServer(app);

And here's the code for the post handling

app.get('/detailed', function(req,res){
    res.send(displayDetailed(results, req));
});
app.post('/detailed', function(req,res){
    res.send('Hello world');
    console.log(req.body);

});

When I post something in localhost:8080/detailed, the hello world returns just fine, but req.body is an empty (returns as {}). The displayDetailed function is a custom function that returns a html string with values extracted from a get request from the google sheets API. Since I'm not working with a saved html document, could this be affecting the process?

like image 427
dropTableUsers Avatar asked May 08 '26 04:05

dropTableUsers


1 Answers

Most of the time req.body is undefined due to missing JSON parser

const express = require('express');
app.use(express.json());

could be missing for the body-parser

const bodyParser  = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

and sometimes it's undefined due to cros origin so add them

const cors = require('cors');
app.use(cors())
like image 61
ANIK ISLAM SHOJIB Avatar answered May 09 '26 18:05

ANIK ISLAM SHOJIB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!