Data is not found in req.body when making a fetch request

I have been attempting to send a fetch request to my server, but I am consistently receiving an empty req.body.

Here is the client-side script:

  const form = document.getElementById('form1')

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const formData = new FormData(form);
    const link = formData.get('link');
    var payload = {
        link
    };
    console.log(payload);

    const options = {
        method: "POST",
        body: JSON.stringify(payload),
        headers: {
            'content-type': 'application/json'
        }
    }
    console.log(options);

    fetch('/api/gtmetriks', options)
        .then(response => response.json()).then(result => console.log(result)).catch(err => console.log(err));
})

And here is the server-side code:

const bodyParser = require('body-parser');
const cors = require('cors')
const app = express()
//Using Cors
app.use(cors())

app.use(bodyParser.urlencoded({
    extended: true
}));
// Parsing application/json
app.use(bodyParser.json())
app.post('/api/gtmetriks', (req, res) => {       
    console.log(req.body);     
})

When I make the post request, I am seeing '{}' in the console output. There are no errors being displayed in the client's browser console either.

Answer №1

It appears that the issue lies in the CORS configuration where you have failed to specify the exact URL for the POST request. Your client is located at http://localhost:3000, while your server resides at http://localhost:3001. Therefore, when making the fetch call, it should be directed to

http://localhost:3001/api/gtmetriks
instead of
http://localhost:3000/api/gtmetriks
.

To rectify this, adjust your fetch function as follows:

fetch('[YOUR SERVER URL]/api/gtmetriks', options)
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(err => console.log(err));
})

With these changes, the functionality should be restored.

UPDATE #1:

This revised code was effective on my setup using a React frontend (running on port 3000) and an Express backend (hosted on port 3001):

Client-side app.js

import React, { Component } from 'react';

export default class App extends Component {
  handleSubmit = () => {
    const payload = {
      link: 'http://tesla.com',
    };

    const options = {
      method: 'POST',
      body: JSON.stringify(payload),
      headers: {
        'content-type': 'application/json',
      },
    };

    fetch('http://localhost:3001/api/gtmetriks', options)
      .then(response => response.json())
      .then(result => console.log(result))
      .catch(err => console.log(err));
  };

  render() {
    return (
      <button
        onClick={() => {
          this.handleSubmit();
        }}>
        Click Me
      </button>
    );
  }
}

Server-side server.js

const express = require('express');
const logger = require('morgan');
const cors = require('cors');

const app = express();

// Set up CORS for cross-origin requests
app.use(
  cors()
);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.post('/api/gtmetriks', (req, res) => {
  console.log(req.body);
  res.sendStatus(200);
});

// Launch server on port 3001
app.listen(3001, () => {
  console.log('Server Listening on port 3001');
});

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

Failed to create a React app using npx create-react-app command

Is this error message familiar to you? The process of creating a new React app in C:\Users\ASUS\Desktop\desk\react1\my-app is running into some issues. An error occurred while installing packages. This may take some time to r ...

Fixing a CSS animation glitch when using JavaScript

I'm facing an unusual issue with my CSS/HTML Check out my code below: a:hover { color: deeppink; transition: all 0.2s ease-out } .logo { height: 300px; margin-top: -100px; transition: all 0.2s ease-in; transform: scale(1) } .logo:hover { transit ...

Tips for broadcasting a router event

Currently, I am working with 2 modules - one being the sidenav module where I can select menus and the other is the content module which contains a router-outlet. I am looking for the best way to display components in the content module based on menu selec ...

What sets apart the functions catch and fail in PromiseJS?

I've been experimenting with Promisejs in my application and I have to say, it's a pretty neat concept. However, I'm a bit unclear on the difference between catch and fail in Promisejs. Can someone please provide some clarity on this? Your ...

Can you explain the variance in these code snippets when implementing React's setState() function?

Can you explain the variance between these two blocks of code? this.setState((state)=>({ posts: state.posts.filter(post=> post.id !==postRemoved.id) })) versus this.setState((state)=>{ posts: state.post ...

Fluid Grid System with columns of specific dimensions

Recently delving into the world of Foundation Framework, I've just begun utilizing it for my projects. My current task involves crafting a responsive design with the help of the Foundation Grid system. Specifically, I've set up a grid layout for ...

Enhancing this testimonial slider with captivating animations

I have designed a testimonial slider with CSS3 and now I am looking to enhance it by adding some animation using Jquery. However, I am not sure how to integrate Jquery with this slider or which plugins would work best for this purpose. Can anyone provide g ...

Autocomplete feature integrated within search bar

I'm currently experimenting with merging MUI autocomplete and MUI searchbar to create a Searchbar that provides suggestions. I have attempted the following: https://codesandbox.io/s/material-demo-forked-cthpv import React from "react"; impo ...

The Enigmatic Essence of TypeScript

I recently conducted a test using the TypeScript code below. When I ran console.log(this.userList);, the output remained the same both times. Is there something incorrect in my code? import { Component } from '@angular/core'; @Component({ sel ...

Adjust the sizes of the points according to the level of zoom

I've been working on creating a dynamic map in d3.js that displays US Science funding agencies as points, with their sizes scaling based on zoom level. I referred to this starter kit for guidance. While there are other solutions out there, they often ...

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...

underscore's _.each() method for callback functions

I've been struggling with implementing my custom _.each() function within another function and keep encountering the issue of getting "undefined" returned. My goal is to utilize _.each() to apply a test function to an array. Despite being aware that t ...

Creating methods in Vue that can alter elements created during the mounted lifecycle hook can be achieved by defining functions

I am trying to implement a button that can recenter the canvas. The idea is that when the button is clicked, it will trigger the rec() method which should reposition the canvas that was created in the mounted() function. However, this setup is not working ...

Is there a way to manage the state of a dictionary nested within a list using React JS?

Below is a snippet of my code. I am attempting to update the state of data (which is contained within datasets) to a value defined by the user. constructor(props) { super(props); this.state={ value:'', set:[], coun ...

Using JavaScript in PHP files to create a box shadow effect while scrolling may not produce the desired result

Issue at hand : My JavaScript is not functioning properly in my .php files CSS not applying while scrolling *CSS Files are named "var.css" #kepala { padding: 10px; top: 0px; left: 0px; right: 0px; position: fixed; background - c ...

Implementing the Audio() Element with JavaScript

I've written the code below, but it's not working properly! When I click on the play button, nothing happens HTML: <button id="play"><img id="playicon" src="img/Polygon 1.svg"></button> JS: I have a variable named 'song0 ...

Using jQuery to toggle the visibility of divs depending on the selection of multiple checkboxes

I found this code snippet that I need help with. <div class="row"> <div class="col-xs-4"> <label class="checkbox-inline"><input type="checkbox" value="draft">Draft</label> </div> <div class="c ...

The process of invoking the parent class's Symbol.iterator function from the child class's Symbol.iterator can be achieved by following a specific

I have two TypeScript classes defined below. class BaseIter { constructor(public a: number, public b: number, public c: number, public d: number){} *[Symbol.iterator](): Iterator<number> { yield this.a yield this.b yield this.c y ...

Having trouble creating a unit test for exporting to CSV in Angular

Attempting to create a unit test case for the export-to-csv library within an Angular project. Encountering an error where generateCsv is not being called. Despite seeing the code executed in the coverage report, the function is not triggered. Below is the ...

Tips on integrating the createjs library into a ReactJS project

Hey there! I'm currently working on developing a canvas-based app using ReactJS, and I need to integrate the CreateJS library. As a newcomer to ReactJS, I've been struggling to figure out the best approach. I've tried two different methods - ...