Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
How to send data from a form to mongodb?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!