What could be causing the request body in ExpressJs to be blank?

Using ExpressJs, I have created a simple app that can handle post requests and form submissions. Below is the code snippet from my index.js file:

require ('./models/db');
const express = require('express')
const app = express()
const bodyParser = require('body-parser');
const hotelController = require('./controllers/hotelController'); 

app.use(express.static('public'))

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json()); 


app.get('/', (req, res)=>{
    res.sendFile(path.join(__dirname, public, 'index.html'));
})

app.listen(30001, () => console.log("listening on port 30001"))

app.use('/hotel', hotelController); 

The controller file accepts POST requests, but I noticed that the request body is always empty, causing the code to break. Here is a snippet from the controller file:

const express = require ('express');
var router = express.Router(); 
const mongoose = require ('mongoose'); 
const Hotel = mongoose.model('Hotel'); 



router.post('/',(req, res)=> {
    console.log(req.body)
    try {
        insertRecord(req,res); 
        
    } catch (error) {
        console.log("An error occurred: " + error.message)
    }

   })

//some more code
module.exports = router; 

Edit 1: See Postman screenshot https://i.sstatic.net/rowlm.png

Edit 2: After changing Content-Type to application/x-www-form-urlencoded in Postman, the request worked with a proper body. However, when submitting from the form, the body was empty again. Check out the code snippet from my messy index.html file for handling the form submission.

<form  name="formInfo"  autocomplete="off" enctype="application/x-www-form-urlencoded" >
    <div class="form-group">
        <label for="inputOwnerName">Name </label>
        <input type="text" class="form-control" id="inputOwnerName" placeholder="Some name" value="Test Name" >
    
    <div class="form-group" style="text-align: center;">
        <button class="btn btn-yellow" style="width: 200px;">Send</button>
    </div>
</form>   

<script> 
    var form = document.forms.namedItem("formInfo");
    form.addEventListener('submit', function(ev) {

    var oData = new FormData(form);
    
    var ownerName = document.getElementById("inputOwnerName").value;

    oData.append("inputOwnerName", ownerName);

    var oReq = new XMLHttpRequest();
    oReq.open("POST", "/hotel", true);
    oReq.onload = function(oEvent) {
        if (oReq.status == 200) {
            // Handle success
        } else {
            // Handle error
        }
    };

    oReq.send(oData);
    ev.preventDefault();
    }, false);
</script>

Answer №1

Could you please update your code to use the following:

app.use(express.json());

When testing in Postman, make sure to set the content type to "application/json" and submit using Raw data.

https://i.sstatic.net/v7IKR.png

UPDATE: I have set my default post headers for json data

https://i.sstatic.net/M3DJt.png

Answer №2

To begin, switch the positions of these two lines in your code

app.listen(30001, () => console.log("Listening on port 30001"))

app.use('/hotel', hotelController);

Additionally, the reason for the empty result may be due to a misconfiguration in the controller. Make sure you have properly exported the router object from the controller file. Here's an example:

---
module.exports = router

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

Generate a hard copy of the data table row without needing to view it beforehand

Here are some records from a table: +--------+---------+-------+----------+--------+ | Name | Address | Phone + Email | Action | +--------+---------+-------+----------+--------+ | Andy | NYC | 555 | <a href="/cdn-cgi/l/email-protection" cl ...

The execution of my code differs between running it locally and in online code editors like CodePen or Plunker

Using jQuery Terminal, I have the following code: function display() { for (var i = 0; i < 100; ++i) { this.echo('line ' + i, { flush: false }); } this.flush(); setTimeout(function() { //thi ...

HTML and JavaScript - Facing issues rendering HTML content during the conversion process from Markdown format

In this particular scenario, my goal is to transform the content inside #fileDisplayArea into markdown format. However, I am encountering an issue where the HTML code within the div element is not being rendered. <div id="fileDisplayArea"># Title ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...

I am encountering an issue where my Vue navbar is successfully changing the route but not updating the corresponding router-view

I have been working on a single-page application using Vue and I encountered an issue with the navbar when navigating through routes. The problem is that after the first click on a navbar item, the route changes successfully but the router-view does not up ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

Encountering a TypeError when utilizing a npm hashtable within an object definition

I am currently working on setting up a basic stream to read and parse JSON data and then add key-value pairs to a hashtable. My end goal is to create a module that can be utilized in another program, but as I'm troubleshooting, I've hit a roadblo ...

Utilizing Express JS for caching static content, excluding rendered HTML pages

Currently, I am in the process of developing a dynamic application that requires HTML not to be cached (as the cart contents can change between page refreshes). In order to achieve this, I have implemented middleware that sets cache-control headers to prev ...

Encountered a CastError in Mongoose when trying to cast the value "Object" to a string

I am struggling with a Mongoose CastError issue within my Node.js API. The problem arises at a specific route where data is being returned appended with some additional information. Despite finding various solutions for similar problems, my scenario seems ...

What is the best way to generate an array containing multiple arrays, each filled with dynamic Divs?

I have the following code that displays a Div when the user clicks on the Add button. For example, if the user clicks the Add button 5 times, then 5 will be displayed with the same controls/inputs under default. html <div ng-repeat="st in stu"> ...

What is the mechanism behind control flow returning in a series of Express middleware functions?

I have some inquiries regarding Express middleware chaining that I'd like to address in this consolidated post since they are interconnected. Q1: While working with a middleware function, if I use send() on the Response, pass it to the next function, ...

Adjusting font size, contrast, brightness, and sound levels on a website with the help of jQuery

My client has a new requirement: adding functionality to increase font size, adjust contrast/brightness, and control sound on his website. When clicking on any of the control images, a slider should appear for the user to make adjustments accordingly. Ho ...

Guide to prompting a browser to download a file using an XHR request

When it comes to downloading files from a server using an XHR request, how can I ensure that the browser initiates the download once the response is received? Additionally, which headers should be included by the server for this process to work seamlessl ...

Do we need to perform session checking for login on POST requests as well?

As a novice in the realm of login systems, I have been utilizing session for authentication. Currently, I have set up a login system with session checking specifically for GET Requests, as they can be accessed directly through the browser's address ba ...

Having trouble verifying a user's password in Postman using "bcrypt.compareSync" with Angular and the MEAN stack

I'm currently working on implementing user authentication before adding a JWT token, and I've encountered an issue where the 'if' check is generating this error: node_modules\bcryptjs\dist\bcrypt.js:265 th ...

Swagger is unable to locate a user schema when utilizing Yaml files

Hello, I am a beginner using Swagger and trying to create simple endpoint documentation. However, I am facing an issue with my schema type and cannot figure out what's wrong. To start off, I organized my folder structure in the root src directory whe ...

Tips for eliminating repeated values in a textbox

<script> $("#filter").on("shown.bs.popover",function(){ $(".popover-content input[type=checkbox]").on("click",function(){ if(this.checked) { this.setAttribute("checked","checked"); } else { ...

Developing an interactive website utilizing AngularJS, WCF Service, and SQL Server

Exploring the possibilities of creating a web application, I stumbled upon AngularJS. With plans to incorporate WCF Service and SQL Server into my project, I am intrigued by what these technologies can offer. I want to ensure that AngularJS aligns with my ...

Guide to positioning a THREE.js plane onto the exterior of a spherical object

Just starting out with Threejs and 3D graphics. I'm interested in learning how to position a plane of any dimensions on the surface of a sphere. Here's an example image of what I'm aiming for: example image ...

Errors are caused when attempting to install third-party JS plugins using npm within a foundation project

I am currently exploring projects involving NodeJS and npm. While experimenting with foundation CLI in Foundation 6.4, I decided to install a 3rd Party JS plugin called chart.js from https://www.chartjs.org/ Following their documentation, I ran the comman ...