Home > Blockchain >  my req.body is empty when i try to get data from a form
my req.body is empty when i try to get data from a form

Time:07-03

I have a user route that render a form, now i wish to take data from the form using a post request, but when i attempt to do so, my req.body is {}. I've already tried using body parser but the result is the same one. I've also tried using the middleware of the encoded url in the app.js instead of the user routes, but that doesn't work ether.

const express = require('express');
const router = express.Router();

router.use(express.urlencoded({extended: true}));

const messages = [
    {
      text: "Hi there!",
      user: "Amando",
      added: new Date()
    },
    {
      text: "Hello World!",
      user: "Charles",
      added: new Date()
    }
]

router.get('/', (req, res) => {
    res.render('index', {title: "Mini Messageboard", messages: messages});
});

router.get('/new', (req,res) => {
    res.render('form')
    
})

router.post('/new', (req,res) => {
  console.log(req.body)  // {}
  res.send(req.body)
})

module.exports = router;

my ejs file:

<!DOCTYPE html>
<html lang="it">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    

    <link rel = "stylesheet" type = 'text/css' href="style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;1,500&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <title></title>
<body>
    <form method="post" action="/new">
        <input placeholder ="Insert your name here" type="text" name="" id="">
        <input placeholder = 'Insert youre message here' type="text">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

CodePudding user response:

The name attribute is responsible for forming key-value pairs in the body of a request. Provide a name attribute for input tags, like: <input type="text" name="*your key*"> and then in backend: console.log(req.body["*your key*"]) will give you the value of input tag.

CodePudding user response:

Your app doesn't know how to parse the incoming request.body. In your code add this line

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

EDIT: Like other answers suggest, you haven't set name attributes to your input fields.

  • Related