Home > Software design >  Express.js req.body is null when form submitted
Express.js req.body is null when form submitted

Time:12-28

I have a simple html form:

<div >
  <h2>Signup for an account</h2>
  <form method="POST" action="/submit-signup">
    <input type="text" title="username" placeholder="username" />
    <input type="password" title="username" placeholder="password" />
    <button type="submit" >Submit</button>
  </form>
</div>

and an index.js with routes:

var bodyParser = require('body-parser')
const express = require('express')
const app = express()
const port = 3000


app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

const Pool = require('pg').Pool
const pool = new Pool({
  user: 'user',
  host: 'localhost',
  database: 'app',
  password: 'password',
  port: 5432,
})


app.get('/', function(req, res) {
  res.sendFile(__dirname  '/index.html');
});

app.get('/login', function(req, res) {
  res.sendFile(__dirname  '/login.html');
});

app.get('/signup', function(req, res) {
  res.sendFile(__dirname  '/signup.html');
});


app.post('/submit-signup',(req, res) => {
  console.log(req.body)
  const username = req.body.username
  const password = req.body.password

  pool.query('INSERT INTO users (username, password) VALUES ($1, $2)', [username, password], (error, results) => {
    if (error) {
      throw error
    }
    response.status(201).send(`User added with ID: ${result.insertId}`)
  })
})


app.listen(port, () => {
  console.log(`App running on port ${port}.`)
})

Every time the form is submitted with answers the request body logs as {} and the error is thrown from the query because of the null value (the column in my database is set to not-null). I've tried most fixes from old stack overflow posts, so any help is appreciated

CodePudding user response:

Your problem cuz you don't use a name tag in HTML form.

<div >
  <h2>Signup for an account</h2>
  <form method="POST" action="/submit-signup">
    <input type="text" name="username" title="username" placeholder="username" />
    <input type="password" name="password" title="password" placeholder="password" />
    <button type="submit" >Submit</button>
  </form>
</div>

CodePudding user response:

You are using the body-parser middleware. This middleware by default will try to parse every http body into a js-object based on a given json value.

As you are sending your data over an HTML form this data is not in JSON representation, but in the data generated by the HTML form.Mozilla Specs

To make this work you either need to iplement a way to read the body sent by the HTML form or use a more modern approach by sending a (REST) JSON request to your express server.

  • Related