Skip to content
Advertisement

I’m trying to print form inputs data on the console of node.js, but the console is showing empty Curly braces

I’m trying to get form inputs data on the console of node.js, but, it’s showing an empty Curly brace.

I used postman to check whether the data is received or not, it’s working well, data has been received successfully on the terminal console.

<——– I have taken the below steps to get the data from POSTMAN ——–>

step-1: created a new collection and selected a post request

step-2: entered request URL (http://localhost/loginandsingup)

step-3: in the header section, selected Content-Type in the key column and the value is application/json

step-4: added some data in the body section

{
   "username": "shyam",
   "email": "kumbamshyam955@gmai.com",
   "mobilenumber": 6547896587,
   "password": "superman145",
   "confirmpassword": "superman145",
   "checkbox": true
}

step-5: finally I clicked on the send button

Output from the postman, on terminal

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Debugger listening on ws://127.0.0.1:61047/e3190b4a-b5a4-4806-9d45-c1f09c74212a
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
application had started successfully on port 80
database conencted successfuly
{
  username: 'shyam',
  email: 'kumbamshyam955@gmai.com',
  mobilenumber: 6547896587,
  password: 'superman145',
  confirmpassword: 'superman145',
  checkbox: true
}

<——– Code to get the form inputs data from locally hosted website ——–>

// I used node.js for the backend //

app.js (Backend code)

const app = express();
const dotenv = require("dotenv");
const path = require('path');

dotenv.config({path: './config.env'})
const User = require('./model/userschema.js')
require('./db/database-connection.js')

const port = process.env.PORT

app.use(express.json()); 

app.use(require('./router/auth'))

const staticpath = path.join(__dirname, '/public');
app.use(express.static(staticpath));

app.set('view engine', 'pug');
app.set('views', path.join(__dirname, '/view'));

const middleware = (req, res, next)=>{
    console.log("hello i'm middleware")
    next();
}

app.get('/', (req, res) => {
    res.status(200).render('home.pug');
})

app.get('/loginandsingup', (req, res) => {
    res.status(200).render('loginandsingup.pug');
})

app.get('/customerservice', (req, res) => {
    res.status(200).render('customerservice.pug');
})

app.get('/product', (req, res) => {
    res.status(200).render('product.pug');
})

app.get('/404', (req, res) => {
    res.status(200).render('404.pug')
})


app.use((req, res) => {
    res.redirect('/404')
})


app.listen(port, () => {
    console.log(`application had started successfully on port ${port}`)
})

router/auth.js (Backend code)

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

require('../db/database-connection');
const User = require('../model/userschema');


router.post('/loginandsingup',(req, res) => {
    const body = req.body
    console.log(body);
    res.json({message: req.body});
})

module.exports = router;

loginandsingup.pug (pug code)

doctype html
html(lang="en")
  head
    meta(charset="UTF-8")
    //- meta(http-equiv='refresh' content='30') 
    meta(http-equiv="X-UA-Compatible", content="IE=edge")
    meta(name="viewport", content="width=device-width, initial-scale=1.0")
    title Mens Fashion | Login & singup
    style
      include ../public/css/login-and-singup-folder/loginstyle.css
      include ../public/css/main-css/style.css
    link(href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css", rel="stylesheet",integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3", crossorigin="anonymous")
    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&display=swap",rel="stylesheet")
  body(style="background: rgba(236, 236, 236, 1)")
    .loding-img-container
      img#loading(src="images/Rolling scg.svg", alt="")
    include navbar.pug
    #login-and-singup-section.container
      #login-and-singup-main-container.container.bg-light
        #login-and-singup-container-1.login-and-singup-container.my-5
              form#login-form
                .mb-3
                    label.form-label(for='exampleInputEmail1') Email address
                    input#login-email.form-control(type='email' aria-describedby='emailHelp' autocomplete="off" placeholder="Enter Email")
                .mb-3
                    label.form-label(for='exampleInputPassword1') Password
                    input#login-password.form-control(type='password' autocomplete="off" placeholder="Enter password")
                button.btn.btn-success#login-submit-btn(type='submit') Sing in
                button.btn.btn-outline-primary#logins-singup-btn(type='button') sing up

        #login-and-singup-container-2.login-and-singup-container.my-5
              .error-images.mb-3
                img(src="images/error icon.png", alt="")
                h1 Error !
                span#error-msg Please Enter Corrext Email
              form#singup-form(method='post' action='/loginandsingup') 
                .mb-3
                    label.form-label(for='username') User name
                    input#username.form-control(name='username' type='text' )
                .mb-3
                    label.form-label(for='email') Email
                    input#email.form-control(name='email' type='Email')
                .mb-3
                    label.form-label(for='mobilenumber') Enter number
                    input#mobilenumber.form-control(name='mobilenumber' type='number')
                .mb-3
                    label.form-label(for='password') Enter New Password
                    input#password.form-control(name='password' type='password')
                .mb-3
                    label.form-label(for='confirmpassword') Confirm Password
                    input#confirmpassword.form-control(name='confirmpassword' type='password')
                .form-check.login-checkbox-container
                    input.bg-danger.border-danger#tandcCheckbox.form-check-input(name='tandcCheckbox' type='checkbox' checked)
                    label.form-check-label.m-0(for='tandcCheckbox') Agree To Our 
                      a.text-danger Terms And Conditions
                .form-check.login-checkbox-container
                    input.border-danger.form-check-input#upcoming-notification(name='offersmail' type='checkbox')
                    label.form-check-label.m-0(for='exampleCheck1') recieve upcomimg offers and events mails
                button.btn.btn-success#new-user-submit-btn(type='submit') Submit
                button.btn.btn-outline-primary#signups-login-btn(type='button') Login

script(type='text/javascript' src='js/loginandsingup.js')
  


script(
  src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js",
  ntegrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB",
  crossorigin="anonymous"
)
script(
  src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js",
  integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13",
  crossorigin="anonymous"
)

Output from the locally hosted website, on terminal

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Debugger listening on ws://127.0.0.1:55622/66b83ad8-4e15-4359-9d7b-1d638262c70a
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
application had started successfully on port 80
database conencted successfuly
{}

**Any solution to this problem

Advertisement

Answer

——->It’s working✌️, after including the body-parser module

const express = require('express')
const router = express.Router()
var bodyParser = require('body-parser')

router.use(bodyParser.json());

router.use(bodyParser.json({ type: 'application/*+json' }))

var urlencodedParser = bodyParser.urlencoded({ extended: false })

router.post('/loginandsingup', urlencodedParser, (req, res) => {
    const body = req.body;
    console.log(body);
    res.json({ message: req.body.username });

})

module.exports = router;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement