Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

req.body undefined after post on express.js v8.1.4?

I want to make a post request with this HTML code:

<!DOCTYPE html>
<form action="/post-test" method="post">
    <input type="text" id="name" />
    <input type="submit" value="submit">
</form>

And then write on the backend console the request.
So here is my backend code:

const path = require('path');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, 'views')));
    
app.use(bodyParser.json());
    
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, "/views/html/test.html"));
});
app.post('/post-test', async function(req, res) {
    const data = req.body;
    console.log(data.name);
    });

When I type something in the input and press submit, the console say undefined.
Where is the problem and have you the solution ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

in the form add the name parameter and put a value, that is insert in the body of the request

<form action="post-test" method="post">
    <input type="text" id="name" name="name"/>
    <input type="submit" value="submit">
</form>

in the backend you access with

req.body.name
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading