I keep receiving a blank request body while using express.js

I'm having trouble retrieving data from my database as the body of the request is empty. I've tried using parse-body and CORS, but it's still not working. I attempted various solutions without success. Backend code:

const bodyParser = require('body-parser');
const cors = require('cors');
const port = 5000;

const app = express();
app.use(cors());
app.use(bodyParser.json());


const MongoClient = require("mongodb").MongoClient;
const uri = "mongodb+srv://example: [email protected]/?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
client.connect((err) => {
  const bookings = client.db("BurjAlArab").collection("bookings");
  console.log("Connected");

  app.post('/addBooking', (req, res) => {
      console.log(req)
    const newBooking = req.body;
    console.log(newBooking);
    bookings.insertOne(newBooking)
      .then(res => {
         res.send(result.insertedCount > 0);
      });
  });
});

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(port);

front end:

const handleBooking = () => {
    const newBooking = { ...loggedInUser, ...selectedDate };
    fetch('http://localhost:5000/addBooking', {
      method: 'POST',
      header: { 'Content-Type' : 'application/json' },
      body : JSON.stringify({newBooking})
    })
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      });
  };

Any assistance would be greatly appreciated.

Answer №1

Make sure to implement the code snippet below in your frontend:

This method utilizes the await keyword

Note that due to the usage of await, the function must be declared as async async function example(){}

async function example(){
    const data = {newData};
        const settings = {
            method: 'POST',
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(data)
        };
        await fetch('/addData', settings); 
    }
}

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

Tips for converting asynchronous function calls into synchronous functions in Node.js or JavaScript?

Imagine you are managing a library that provides access to a function called getData. Users utilize this function to retrieve real data: var output = getData(); In the background, the data is stored in a file, so you have implemented the getData functi ...

Another approach to utilize JavaScript for populating content into a <div> container?

Upon loading the page, I aim to display a message in the <div> element. Below is the HTML and JavaScript code I have implemented: <body onload="printMsg()"> <div id="write"></div> </body> function printMsg() { var no ...

Transferring user-selected values from JavaScript to a PHP file

When sending values from JavaScript to a PHP file, everything works smoothly when all the values are collected. Step1 functions perfectly as both fields are mandatory. However, in Step2, values are only sent when all the fields are selected. There are co ...

Update not reflecting on global variable across all Phaser states

Whenever you are on the helm state and adjust the warp factor before pressing the engage button, it triggers the function engage which sends out the necessary data. Upon receiving this data, the server checks if the inertial dampeners are active or not, th ...

Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project ...

Retrieving the first child in a tree via URL parameters using JavaScript, rather than the currently selected one

I'm currently facing a specific issue with my webpage and I will elaborate on what's happening. Within my page, I have created a list containing multiple sections. Here is an example of how it looks: <ul class="menu__list--nested active& ...

Navigate through the JSON object and generate all possible combinations of nested elements

Here is a JSON object that I need to iterate through in order to generate all possible nested group names: { "groups": [ { "group": "group1", "childrens": [ { "group": "group1_1", ...

What is the process for logging a personalized error statement using the pino-http module in tandem with express?

In our application, we utilize pino-http along with express to log the REST API requests that are received. When an error occurs, we make sure to log the error object to provide insights into what caused the issue. However, a challenge we face is that wh ...

Previewing multiple selected files in Angular interface

As a newcomer to Angular, I am currently working on a feature that involves selecting multiple files and displaying their previews before uploading them to the server. While my code works correctly when individual files are selected one at a time, it fail ...

Steps to Embed an Image File in a MERN Stack Application

I'm attempting to load an image from a file inline because I need to pass data (the image name), but nothing seems to be working. It doesn't work whether the image is inside the src folder or outside in the public folder. Here's what I trie ...

Error: The variable "deleted1" is not declared and cannot be used on the HTML button element's onclick

Hello, I need assistance from someone. I encountered an error message after trying to delete a row even though I have declared the button already. Error: deleted1 is not defined at HTMLButtonElement.onclick Could it be due to the script type being modul ...

How can you remove the add button in React Material Table?

Within the material table, there is a feature that allows for the conditional hiding/disabling of action buttons. Is there a way to do the same for the Add button located at the top of the table? See screenshot below ...

Unable to Retrieve JSON Output

PHP Code: $contents = ''; $dataarray = file('/location/'.$_GET['playlist'].''); //Loading file data into array $finallist = ''; //Extract Track Info foreach ($dataarray as $line_num => $line) //Loopin ...

Retrieve the index of several callbacks created within a loop iteration

While working with an API function that requires a callback in a for loop, I encountered an issue where the callback needed to be index-specific. However, I couldn't alter the willCallBack function (as it's part of the API) and didn't want t ...

What is the best approach in AngularJS for implementing a browser modal that returns a promise?

How can I implement a custom modal in my code that allows me to perform an action only after the user clicks 'okay'? var modalInstance = this.$modal.open({ templateUrl: '/app/tests/partials/markTest.html', controller: ['$sc ...

Should the button be eliminated in favor of simply requesting input from the user?

Looking for help with my code. How can I set it up so that when the HTML file is clicked on, it prompts for input instead of displaying a button? I'm new to coding and could use some guidance. <!doctype html> <html> <head> <meta ...

Exploring the concept of jQuery handler functions

Within my code, I have the following: <script type="text/javascript"> $(document).ready(function (e) { $('#EventCreate').click(function (e) { location.href = '@Url.Action("Create", "AEvents")'; }); ...

Inserting data into a table using variables in Mssql database management system

I'm really struggling to find a way to safely add my Variables into an MSSQL server. I've tried everything. Could someone please help me and provide the solution for adding my Variables into the Database? It is crucial that I prevent any possib ...

What is the best way to extract ABC 12005 from strings like ABC000012005 and ABC0000012005?

My task involves parsing a string with values like ABC000012005,ABC0000012005. The desired output is to extract the prefix and numbers without leading zeros, formatted as ABC 12005, ABC 12005 ...

Lock in the top row (header row)

In a node.js application: How can I lock the top row of a table in place, similar to Excel's freeze panes feature? I think this might involve using some CSS styling, but I'm not exactly sure how to achieve it. When I tried using fixed, the entir ...