Home > OS >  why unable to display value of title?
why unable to display value of title?

Time:12-06

I am trying to output the value of title which i entered in the form in the /Add-Product link

Here is my app.js code

const http= require('http');
const path= require('path');

const express= require('express');

const app= express();

app.set('view engine', 'ejs');
app.set('views', 'Views');

app.use(express.static(path.join(__dirname, 'Public')));

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

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

app.get('/add-product', (req, res, next)=>{
    res.render('addProduct');
});

app.post('/add-product', (req, res, next)=>{
    
    
    console.log(req.body.title);              //uable to display value of req.body.title
  
    res.redirect('/');
});


app.listen(3000);

form part of the addProduct.ejs

 <main>
        <form action="/add-product" method="POST">
            <p>Title</p>
            <input type="text" name="title" id="title"/>
            <p>Price</p>
            <input type="text" name="price"/>
            <p>Description</p>
            <input type="text" name="description"/>
            <button type="submit">Submit</button>
        </form>
    </main>

Unable to figure why the req.body.title is throwing an error as:Cannot read property 'title' of undefined Please guide me on what i am missing.

CodePudding user response:

By default, form submits the data to server in the content type of application/x-www-form-urlencoded. So you need to configure node js to receive this type of content. Use bodyParser to read the request body with json and encoded content.

Usage:

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
  • Related