Why is req.body returning empty?

I'm facing an issue with sending data to my MongoDB database. When using router.post, my req.body appears empty. However, if I replace req.body with the data from my send function like User(req.body), the data is successfully sent to MongoDB.

Below is the router code that I'm working with. The router.get works perfectly, returning the database tables correctly on the /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

Here is the code from my index.js:

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 the function I use for sending 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);
}

Answer №1

I've noticed something a bit odd - you're using both a json body-parser and express.json(). They essentially do the same thing, but since body-parser is deprecated, it could potentially be causing issues.

Additionally, there's no need to import it again in the routes. Adding app.use(express.json()) in index.js will ensure it works for all endpoints/routes.

Why not try this refactored code:

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

Answer №2

Everything ran smoothly with the following code snippet:

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) {
    // ...
}

One notable difference lies in using: app.use(router)

It's important to mention that in the provided code, the line:

router.use(express.json())

can be substituted by (utilizing body-parser):

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a table with a static first column and vertical text positioned to the left of the fixed column

To create a table with the first column fixed, refer to this fiddle link: http://jsfiddle.net/Yw679/6/. You also need a vertical text to be positioned to the left of the fixed column in a way that it remains fixed like the first column. The disparities be ...

The size of the array within the object does not align

I've run into a roadblock while attempting to implement the tree hierarchy in D3. Initially, I believed that I had correctly structured the JSON data, but upon inspecting the object using Developer's Tool, a discrepancy caught my eye: https://i. ...

How do you incorporate ScrollTop animations using @angular/animations?

I'm attempting to recreate the animation showcased on Material.io: https://i.stack.imgur.com/OUTdL.gif It's relatively easy to animate just the height when clicking on the first card in the example above. The challenge arises when you click on ...

Is it necessary for a container component to always be connected to Redux?

As I prepare to embark on a new React project, I am reflecting on my past experiences to establish guidelines for structuring the application. Here are some principles that I hold true: Redux serves as the central repository for data in the entire appli ...

To prevent the page focus from shifting, make sure to force click on a blank link

My question involves an empty link: <a href="#" id="stop-point-btn">+ add stop-point</a> This link is connected to a JavaScript function: $("#stop-point-btn").bind("click", addStopPoint); The JS function simply inserts content into a specif ...

"Generate a series of dropdown menus with choices using either jQuery or AngularJS from a JSON dataset

I'm in need of assistance. I want to generate select dropdowns dynamically based on data retrieved from my REST API, which is in JSON format. How can I dynamically inject these selects into my HTML? Below is an example data structure: JSON data fetch ...

"Dynamic" visual in a Vue.js development scheme

Utilizing Vue.js for the development of a hybrid mobile application has been my current focus, with the Quasar framework serving as a key component. Recently, I incorporated an image into the application using the <img /> tag and utilized the followi ...

How can I retrieve the Id from a TextField in MUI when the select property is activated?

I am struggling to retrieve the id from the mui TextFiled element when the select property is activated. However, I am always getting an undefined value. Here is the code snippet: export default ({ onChangeSelect, input, label, options, ...

Top method for keeping track of most recent function outcome

Over time, I have become accustomed to utilizing the bind method to store the previous result of a function and keep track of it for future use. This allows me to easily concatenate or join the previous string with a new string without needing external var ...

Reverse the log of an array

How can I reverse an array in JavaScript, with each item on a new line? function logReverse(input) { let reverse = input.reverse(); return reverse; } // The current implementation does not display items on different lines logReverse(['HTML&ap ...

The MEAN stack application experiencing functionality issues on the AWS EC2 server

I successfully built a SaaS app using the MEAN stack, which is running smoothly on both my local machines and server. However, I am encountering an issue with my AWS EC2 instance. Whenever I send a large data query to the server, it stops responding and I ...

Discovering the process of searching for options in a dropdown menu

I'm currently implementing select2min.js for a dropdown select box. Currently, it's functioning well for a single drop-down: <select> <option>abc</option> </select> It works fine with the following code: $("#myId0"). ...

Encountered a global secondary index error while trying to create a new table

I'm in the process of setting up a table with a global secondary index using the JavaScript SDK within Node.js: var messagesTableParams = { TableName : "Messages", KeySchema: [ { AttributeName: "to", KeyType: "HASH"}, //Partition key ...

Exploring the world of jQuery and JavaScript's regular expressions

Looking to extract numeric characters from an alphanumeric string? Consider a scenario where the alphanumeric string resembles: cmq-1a,tq-2.1a,vq-001,hq-001a... Our goal is to isolate the numeric characters and determine the maximum value among them. Any ...

Unexpected box-shadow issue with Material UI's Box component

During the development of my application, I encountered an issue with rendering a list of items. The state consists of a simple array containing elements with a name, an identifier, and a selected key that determines whether special styles should be applie ...

Trouble with Slides.js jQuery plugin loading properly on Chrome and Safari, works perfectly on Firefox

I have implemented a slideshow plugin from on my website: . The issue I am facing is with its compatibility in different browsers. When viewed in Firefox, the slideshow functions perfectly as expected. However, in Chrome or Safari, the slideshow fails to ...

Issue with Event Listeners Not Reattaching Upon Clicking "Play Again" Button in Rock-Paper-Scissors Game

Description: I have created a Rock-Paper-Scissors game using HTML, CSS, and JavaScript. The game functions properly initially, allowing users to select their choice and play against the computer. However, after completing a game and clicking the "Play Agai ...

Node.js configuration for setting the maximum size of old space

As someone who is new to working with nodejs and mongodb, I encountered an issue while attempting to read about 100000 records from my mongodb using a nodejs application. Upon trying to retrieve the 100000 records, I came across the following error message ...

I have already configured cors in my Node.js Express application, but I am still encountering the same error related to cors

I've already implemented cors in my express app, but I'm still encountering an issue: XMLHttpRequest cannot load http://localhost:3000/api/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow ...

Click the Button to Trigger Database Update

I have been struggling with updating a dynamic table that allows inline editing and dynamically adding rows. My goal is to click a save button that triggers an UPDATE query to modify the database. Unfortunately, I can't seem to figure it out on my own ...