Performing a fetch() POST request in Express.js results in an empty body object being generated

Purpose: Implement a function in fetch() to send specified string data from the HTML document, for example "MY DATA"


Here is the code snippet:

HTML Code:

<!DOCTYPE html>
<html>
<body>

<script type="text/javascript">
    function fetcher() {
      fetch('/compute',
        {
          method: "POST",
          body: "MY DATA",
          headers: {
            "Content-Type": "application/json"
          }
        }
      )
      .then(function(response) {
        return response.json();
      })
      .then(function(myJson) {
        console.log(myJson);
      });
    }
</script>

</body>
</html>

Server.js File:

var express = require("express");
var app     = express();
var compute = require("./compute");
var bodyParser = require("body-parser");

// The purpose of "extended: false" is uncertain
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/compute', (req, res, next) => {
    console.log(req.body);
    var result = compute.myfunction(req.body);
    res.status(200).json(result);
});

Current Output: console.log(req.body) displays {}

Expected Output: console.log(req.body) should show "MY DATA"

Important Points:

  1. I attempted sending the body in the fetch() function as
    body: JSON.stringify({"Data": "MY DATA"})
    but received an empty {}.
  2. I suspect that either my fetch() request or my bodyParser() configuration is incorrect.

Answer №1

Make sure to include the following line alongside your existing bodyParser app.use() just before:

app.use(bodyParser.json());

By adding this, you will allow bodyParser to effectively parse content type of application/json.

Hopefully this advice proves useful!

Answer №2

After a moment of realization, I now understand the concept of bodyParser.urlencoded. (source: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions)

This middleware specifically parses urlencoded bodies.

Resolution

I made the following adjustment to the fetch() request:

body: "MY DATA",
headers: { "Content-Type": "application/json" }

changed to:

body: JSON.stringify({"Data": "MY DATA"}),
headers: { "Content-Type": "application/x-www-form-urlencoded" }

This simple change successfully resolved the issue! The console output was:

{ '{"Data":"MY DATA"}': '' }

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

Troubleshooting: Why is my AngularJS Controller not functioning properly

I attempted to run a basic Angular example utilizing a controller, but it does not appear to be functioning correctly. Below is the HTML code: <!DOCTYPE html> <html ng-app = "app"> <head> <title></title> ...

Preventing default form submission in jQuery: How to cancel it when a certain condition is met

I have a contact form where I validate the input values upon clicking on the submit button. If there is at least one empty input, I trigger an alert and prevent the form submission by using preventDefault. However, if all inputs are filled and submitted, t ...

Maintain the scrollable feature of the element until the final content is reached

I'm struggling to come up with the right keywords to search for my issue. I've tried using Google, but it seems my search terms are not effective. The problem I'm facing involves two relative div elements with dynamic content. This means th ...

Tips for setting up a new file for router functionality

How can I properly export the router module for use with the showscreen = true statement? This is a simplified version of what I am trying to achieve. server.js var express = require('express'); var app = express(); var http = require('htt ...

Is there a way to effortlessly launch a new window with just a single click?

I'm encountering an issue with a function that is supposed to open a new window when a button is clicked. Strangely, on the first click, nothing happens, but on the second click, the window finally opens. Here's my code: Script <script src ...

Accessing node postgres and fetching combined fields with duplicate names

Currently, I am developing a node.js application that utilizes the pg package to connect to a PostgreSQL database. The problem I am encountering involves querying data using a join statement and finding that fields from one table overwrite those from anoth ...

Filtering out section boxes does not eliminate empty spaces

Link to Fiddle I've run into a bit of a roadblock while trying to filter my section box for a project I'm currently working on. The issue I'm facing is that instead of collapsing the first section box to display only the filtered options, i ...

Ways to showcase information from an angular service

I'm struggling with displaying data from a service in my HTML view using AngularJS. My goal is to show a list of submitted forms called Occurrences in the view. When clicking on a list item, I want to be able to view all the data fields submitted thro ...

What steps should I follow to track an event using Firebug?

When I examine the element, how can I discover all of the events that are attached to it? ...

Tips for maintaining the longevity of a NodeJS Passport session

Currently using Node, Express, and Passport for authentication. Additionally, persisting session information to Redis with a maxAge setting on the session cookie to expire in one hour. Everything is functioning as expected but facing an issue where the ses ...

When you print document.getElementById('idname').value, it only displays [object HTMLInputElement]

Currently, I have a Tamper-monkey script in place that is designed to scrape specific text from a single page. The script's job is to extract the values of three buttons named pick_0, pick_1, and pick_2 from the page and display them in a designated b ...

I'm having trouble with my basic routing set up and I'm struggling to understand why it's not working

I'm currently working on a node tutorial and facing some challenges with my routes.js file. Previously, everything was functioning well today as the Node server was able to read the file. However, it seems to be ignoring it now for some unknown reaso ...

Having difficulty in sending emails through Nodemailer using a Google App Password

I implemented a route in an API that involves sending an email to users upon signing up. Utilizing nodemailer and a Google App password, everything was running smoothly until February 3rd, 2023 when the connection suddenly ceased without any changes to the ...

Ways to update or incorporate new data within JavaScript

I'm currently experimenting with ways to incorporate additional text or even AdSense into what I believe is a .js file. There's an operational lightbox feature with a descriptive caption at the bottom, and that caption is what I want to modify. ...

The changes made to the state array in react.js are not reflected in the DOM

In my React game implementation, I have the board set up as a two-dimensional array in the initial state of the parent component. The tiles on the board are rendered by looping through this array. Each tile receives a function as a prop that allows it to m ...

Challenges arise when trying to load CSS on an EJS page in conjunction with using res.redirect()

When using Express with EJS, my base route is set as follows: router.get("/", productsData.getProducts); The "productsData" is sourced from my controllers page and the code snippet within that page is as follows: exports.getProducts = (req, res, next) => ...

How can I prevent users from selecting text when they right click using JavaScript?

My custom context menu on canvas works well, but I'm facing an issue with Text elements. When I try to right-click on a text element, it triggers text selection as if double-clicking. I attempted to use the following code: document.addEventListener(& ...

Modify the hash URL in the browser address bar while implementing smooth scrolling and include the active class

I have implemented a smooth scroll technique found here: https://css-tricks.com/snippets/jquery/smooth-scrolling/#comment-197181 $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replac ...

managing nested JSON arrays in JavaScript

I have a straightforward task with handling a simple array that is divided into two parts: a group of vid_ids and a single element named page. Initially, I was iterating through the vid_id array using a for loop. However, upon adding the page element, I en ...

What is the optimal method for storing images on a website built with expressjs and mongodb?

I am currently diving into express, nodejs, and mongodb for a project I'm working on - creating a website for a clothing store. The client will be uploading new images every 2 days, which need to be displayed quickly as thumbnails on the website. User ...