Why passing JSON parameters from HTML to Node.js results in body parameter is undefined

102 Views Asked by At

I'm playing with Node.js for the first time trying to pass parameters from a form to my server and print them on the console

my html

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Hello Node</title>
    </head>

    <body>

    <h1> we have a website</h1>
    <form action="/contact" enctype="application/json" method="POST">
        <input name="firstName" placeholder="firstName" type="text" size="30" />
        <input name="lastName" placeholder="lastName" type="text" size="30" />
    
        <input name="submit" type="submit" value="Send This">
    </form>

    </body>
</html>
  • i've tried both with and without enctype="application/json"

my app.js file

const express = require('express'); 
const app = express();
const bodyParser = require('body-parser') 
var jsonParser = bodyParser.json()

app.listen(3333, () => {
    console.log("Server is up and listening on 3003"); //print to the server console (the terminal!!)
})

app.post("/contact", jsonParser, function (req, res) {
  console.log("in /contact");
  console.log("request body:" + req.body);
  console.log("request body first name:" + req.body.firstName);
  console.log("request query first name:" + req.query.firstName);
})
  • I've tried with and without app.use(bodyParser.json({ type: 'application/*+json' }))

Output:

[object Object]

request body first name:undefined

request query first name:undefined

1

There are 1 best solutions below

1
sawim On

According to Mozilla documentation application/json content type is not allowed to be set as enctype value, so you can either send json using javascript or add support for application/x-www-form-urlencoded via app.use(bodyParser.urlencoded({ extended: false }))