Home > Back-end >  req.body is empty, why?
req.body is empty, why?

Time:10-21

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) instade 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)
}

CodePudding user response:

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')
})

CodePudding user response:

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

  • Related