Home > Back-end >  "name is not defined" in express app (registration form page)
"name is not defined" in express app (registration form page)

Time:11-14

I am trying to make a simple registration form using express but in post request while I am trying to console.log the "name" is showing an error i.e name is not defined but in form input, I mentioned the name="name". please help me to solve this as I am new to this. Thank You.

in app.js file:

var express = require('express');
var path = require('path');
var port = 5000;
var app = express();

app.set('views', path.join(__dirname, "views"));
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, '/public')))

app.get('/', (req,res)=>{
    res.render('index');
})
app.get('/register', (req,res)=>{
    res.render('register');
})

app.post('/register',(req,res)=>{
    const name = req.body.name;
    console.log(name);
    res.render('index');
})

app.listen(port, ()=>{
    console.log(`Server is running at port ${port}`);
})

in register.hbs :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/stylesheets/style.css">
    <title>Registration Website</title>
</head>
<body>
    <h1>Welcome to our Registration page</h1>
    <div class="container">
        <div class="form-box">
            <form action="/register" method="post"  enctype="multipart/form-data">
                <input type="text" name="name" placeholder="Enter Your name" autocomplete="off">
                <input type="email" name="email" placeholder="Enter Your email" autocomplete="off">
                <input type="password" name="password" placeholder="Enter password" autocomplete="off">
                <input type="password" name="cpassword" placeholder="Confirm your password" autocomplete="off">

                <button type="submit" name="submit">Register</button>
            </form>
        </div>
    </div>
</body>
</html>

file structuring enter image description here

CodePudding user response:

You should consider using the body-parser js module, so as to read the form fields data on processing a POST of form. See the details of body-parser , helpful answers here.

  • Related