0

I am created a nodejs project the structure of py project is: enter image description here

api.js is:

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

const add = require('../model/myModel');


router.get('/',function(req,res){
    res.render('myForm');
});


router.post('/add', (req, res) => {
    console.log(req.body)
    n = req.body.name,
    phone = req.body.phone,
    console.log(`name = ${n}`)
   
   let obj = new Address({
     name: n,
     phone: phone,
    });
   
   // add this instance to the database.
   obj.save()
   .then((address) => {

       res.send(address);
       })
    .catch((err) => {
        console.log(error);
        });
   });

module.exports = router;

and my app.js is:

const express = require('express');
const mongoose = require('mongoose');
const route = require('./route/api');
//Initialize express app
const app = express();

// Connecting to DB
const dbPath = 'mongodb://localhost:27017/testdb';
const dbOptions = {useNewUrlParser: true};


mongoose.connect(dbPath, dbOptions).then(()=>{
    console.log(`We are connected to our database ${dbPath}`);
}).catch((error)=>{
    console.log(`We are note able to connect to our database: ${error}`);
});

app.use(express.static('public'));
app.use(express.json());
app.set("view engine", "ejs");

// initialize routes
app.use("/api", route);

//Initialize the sever
app.listen(3000, () => {
    console.log('sever listening on port:3000');
});

and myForm.ejs is:

enter image description here

So, I want to be able to enter the data in myForm.ejs and save this data in the database. But when I fill the form and press submit my req.Body is an empty object. Where is my error?

2 Answers 2

1

Server side you need additional parser middleware

app.use(express.json());
app.use(express.urlencoded({ extended: true })); //add this line

Client side your form should use /api/add, and not /add

Sign up to request clarification or add additional context in comments.

Comments

0

Use async await as it is a call from the database use this

router.post('/add', async (req, res) => {
console.log(req.body)
n = req.body.name,
phone = req.body.phone,
console.log(`name = ${n}`)

let obj = new Address({
 name: n,
 phone: phone,
});

await obj.save()
.then((address) => {
   res.send(address);
   })
.catch((err) => {
    console.log(error);
    });
});

1 Comment

Please always provide code with correct formatting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.