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

252
Views
req.body is empty, why?

I want to send some data to my MongoDB database, but in router.post my req.body is empty, if I use stuff that I put in my send function in User(req.body) instead of req.body data will be send to my MongoDB database correctly.

This is my router that I use, router.get work fine, it return database tables correctly on /api page:

const router = require("express").Router();
const User = require("./model/models");
const parser = require("body-parser").json();

router.get("/", async (req, res) => {
    const data = await User.find({});
    res.json(data);
});

router.post("/",parser,async (req, res) => {
    console.log('1')
    console.log(req.body)
    console.log('2')
    parser.v
    await User(req.body).save();
    res.json({"msg": "ok"});
});

module.exports = router

This is my index.js file code:

const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const parser = require("body-parser").json();
var path = require('path');

app.use(express.urlencoded(true));
app.use(express.json());
app.use(parser);
app.use('/',require("./routes/routes"))
app.use(express.static(__dirname +'/public'))
app.use("/api", require('./data/api'))

app.listen(5000,function(){
    console.log('server is alive')
})

This is function that what I use to send data:

const btn1 = document.getElementById('btnEnter')
let Login = "123"
btn1.addEventListener('click' ,e=>{
    send({newsTxT : "someTextHere",newsZag:"someZag",author:"SomeAuthor"})
})
const send = async(body) => {
    let res = await fetch("/api", {
        method: "post",
        header: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        body: JSON.stringify(body)
    });
    let data = await res.json();
    console.log(data)
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The following worked fine:

const express = require("express")
const app = express()
const router = express.Router()
router.use(express.json())

app.use(router)

router.post('/api/user', function(req, res) {
    // ...
}

I see the difference may be using the: app.use(router)

Note that in the above code the statement:

router.use(express.json())

can be replaced with (using the body-parser):

const bodyParser = require('body-parser')
router.use(bodyParser.json())

This worked fine with express version 4.17.1, body-parser version 1.19.0 and NodeJS version 12.18.3

about 4 years ago · Juan Pablo Isaza Report

0

The only weird thing I see is that you are using a json body-parser and also the express.json() both technically do the same, but body-parser is deprecated so it might be causing a bug.

Also you don't have to import it again in the routes, placing app.use(express.json()) at index.js will make it work for all endpoints/routes.

See how this refactor goes:

const router = require('express').Router()
const User = require('./model/models')

router.get('/', async (req, res) => {
  const data = await User.find({})
  res.json(data)
})

router.post('/', async (req, res) => {
  console.log('1')
  console.log(req.body)
  console.log('2')
  await User(req.body).save()
  res.json({ 'msg': 'ok' })
})

module.exports = router

index.js

const express = require('express')
const app = express()
var path = require('path')

app.use(express.urlencoded(true))
app.use(express.json())

app.use('/', require('./routes/routes'))
app.use(express.static(__dirname + '/public'))
app.use('/api', require('./data/api'))

app.listen(5000, function () {
  console.log('server is alive')
})
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!