Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda