Node.js/Express - unable to retrieve client body data on server

I am able to retrieve data from express but I am facing issues when trying to post data to express...

client:

<html>
  <button onclick="myFunction()">send</button>
  <script>
    const data = {"experience" : 0};
    function myFunction(){
      fetch("/post", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      })
    }
  </script>
</html>

express:

Initially, I was getting an undefined response, but after adding express.json(), the response changed to "{}". Both client and server connections seem fine, however, there doesn't appear to be a body where the data is stored. I tested my client code by posting data to webhooks.site, and it worked perfectly. I believe there might be a simple mistake somewhere... By the way, I am using react and express, although I have simplified my code here. Any suggestions would be highly appreciated.

const express = require("express");
const app = express();

app.post("/post", express.json() ,function (req,res){
  console.log(req.body)
})

const port = 5000;

app.listen(port, () => `Server running on port ${port}`);

Answer №1

When working with Express, I find it necessary to utilize packages like Body Parser or Busboy to access data in the POST body.

For instance, an implementation could resemble the following:

const bodyParser = require('body-parser');

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

app.post("/post",(req,res,next)=>{
  console.log(req.body);
})

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

Encountering parameter issues while working with Google Maps React in TypeScript

Currently, I'm utilizing TypeScript in this particular file. import React, {Component} from 'react' import {Map, InfoWindow, Marker, GoogleApiWrapper, mapEventHandler, markerEventHandler} from 'google-maps-react'; import { coordina ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Toggle the Editable Feature in AngularJS JSON Editor

Currently, I'm utilizing a library called ng-jsoneditor that is available on GitHub. I am attempting to switch the state of an element from being editable to being read-only. To indicate that an element should be read-only, I need to specify the onE ...

Troubleshooting: Issues with accessing object properties in a function in AngularJS

In my controller, I have a function that checks the day and changes the isOpen property of an object based on the time. The object is retrieved using the code snippet below: $http.get('js/data.json').success(function(data) { $scope.locations = ...

What is the process for implementing a button that removes information from a MongoDB database?

I have been working on making a button functional that will delete specific data by passing its id. However, I am encountering an issue where the button does not perform any action when clicked; there are no errors or visible changes. Below is the code fo ...

Using PM2 to Manage Your PHP Scripts in Cluster Mode

Currently, I have been effectively managing single instances of PHP daemons with PM2, and so far everything is running smoothly! When it comes to managing Node.js/IO.js apps with PM2, I can easily launch them in cluster mode without any issues. However, t ...

Multiple instances of node.exe processes are being spawned due to the Task Runner Explorer in Visual Studio 2015

Currently, I am utilizing gulp for the development of a website project. The task runner explorer in Visual Studio 2015 is able to detect the gulp file, allowing me to execute tasks from there. However, there has been an issue where numerous node.exe proce ...

Reacting with Node.js: Capturing a selected option from a dropdown menu and storing it in the database

On my React frontend, I have a select dropdown like this: <select name="level" value={level} onChange={this.handleChange} className="form-control"> <option>Begineer</option> <option>Intermediate</option> <option> ...

What is the best way to prevent automatic trimming in EJS variable assignment in Node.js?

When I attempt to write a variable from the database into an EJS table, it is being displayed with default trimming by the EJS template. However, I would like to display the variable from the database without any default trimming. I consulted the EJS temp ...

Can the text value be read and its strings changed?

I need to modify the message inside an H2 element with the code provided below. I want to change the text from No results were found for this query: <em class="querytext"> to "No results were found by hello world!, but the catch is that I cannot di ...

Adjusting the URL variable based on the selected checkbox option

My mobile website offers users the option of a bright or dark interface using a checkbox styled like an iPhone IOS7 switch. The functionality is working as expected, but I'm now facing an issue with passing the status of the checkbox between pages. I ...

What issue is present in this Node.js one-line conditional statement?

Check it out: ( result.username === user.username ) ? res.status( 500 ).json( "That username is already taken." ) : res.status( 500 ).json( "That email has already been used." ) Shouldn't this execute the first part, res.status( 500 ).json( "That us ...

Node.js error: HTML audio file returns 404 on server but plays fine when accessed directly as an HTML file

I'm facing an issue with an HTML page that contains an autoplay tag for a song (the file is in mp3 format). When I open the page as a local file on my Mac, the song plays fine. However, when I try to run it using a node.js file with socket.io, the son ...

JavaScript slowness

Currently, I am developing a test page that consists of buttons triggering various scripts. One of the functionalities I am trying to implement is changing the background color every second for 5 seconds, cycling through a total of 5 different colors. Desp ...

What are the essential Bootstrap CSS and JavaScript files that need to be connected to our HTML document?

I recently downloaded the most recent version of Bootstrap, which is version 4. Upon extraction, I noticed that it includes two folders: one for CSS and the other for JS. The CSS folder consists of approximately 12 CSS files, while the JS folder contains ...

Format the following code block using the Jade syntax:

When defining a code block in Jade, I'm uncertain about whether the dash - at the beginning of the code is necessary. Consider the following working code snippet (taken from ): if name == "Bob" h1 Hello Bob else h1 My name is #{name} This alter ...

Leveraging the power of React and Nodejs to seamlessly share code across both the front-end

Currently, my front-end is built in React and backend is developed using Nodejs with the Adonisjs framework. I am looking to share some code between the client and server components of the application. Unfortunately, due to company policies, my team is una ...

Remove data from Firebase that is older than two hours

I need to implement a solution to automatically delete data that is older than two hours. Currently, I am iterating through all the data on the client-side and deleting outdated entries. However, this approach triggers the db.on('value') function ...

Code that changes every occurrence of a particular filtered selection of HREF values to a different value

When faced with the limitation in Firefox where links cannot be opened in a new tab if they have a HREF tag diverting to a function, it might be necessary to utilize a script to convert them to an actual HREF. Understanding the functionality of foo: func ...

[Vue alert]: Issue in created function: "TypeError: Unable to assign value to undefined property"

I'm currently in the process of developing a VueJS application where I have implemented a child component called Child.vue that receives data from its parent. Child.vue export default{ props:['info'], data: function(){ ...