No content sent in the request body while implementing fetch

Attempting to send graphql calls from a React component to a PHP server using the fetch method for the first time.

The setup involves React JS on the client-side and Symfony 4 on the server-side. Despite indications that data is being sent in the browser dev tools, all calls result in an empty body on the server side.

Surprisingly, when utilizing graphiql, the requests are successful. I've been trying to replicate the graphiql request structure in React, but the body consistently remains empty.

This is the code snippet showcasing the fetch call:

fetch('/api', {
    'method': 'post',
    'credentials': 'include',
    'headers': {
        'Content-Type': 'application/json',
    },
    'body': JSON.stringify({
        "query": "mutation {UpdateActionStatus(input: {actionId: 61, status: TO_DO}) { id }}",
        "variables": null
    }),
}).then(r => {
    console.log(r.json());

    return r.json();
}).catch(error => {
    console.log('There has been a problem with your fetch operation: ', error.message);
});

Various experiments have been conducted by setting the 'mode' parameter to values like 'cors', 'no-cors', 'same-origin', 'navigate', yet none of these configurations seem to work as expected.

Testing has been done on both Firefox and Chrome browsers, however, without any success.

Even changing the content type to 'application/graphql' did not yield positive results.

Despite reviewing several solutions proposed on platforms like stackoverflow, the issue of empty response bodies persists with no resolution in sight.

An alternative approach involving a more simplistic fetch call was also attempted, unfortunately with similar futile outcomes. It appears there might be an underlying reason preventing the use of fetch altogether, which currently remains unidentified.

fetch('/api', {
    'method': 'post',
    'credentials': 'include',
    'headers': {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    'body': 'test=test',
});

What steps can be taken next? Is there something obvious that is being overlooked in this scenario?

Answer №1

Ensure that the Content-Type and Accept headers are being sent correctly.

'Accept': 'application/json',
'Content-Type': 'application/json', 

Answer №2

My current approach involves utilizing GraphQL along with React, rather than relying on the traditional fetch method, and overall it has proven to be quite effective.

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

What is the best way to showcase navigation and footer on every page using AngularJS?

I'm in the process of building a Single Page Application. I've decided to create separate components for Navigation, Section, and Footer. The Navigation and Footer should be displayed on every page, while only the Section content changes when nav ...

Firefox not rendering responsive YouTube embed properly

This method of embedding seems to be functioning well on all browsers except for Firefox; I took advantage of a free trial at crossbrowsertesting.com to verify. I’m not using a direct iFrame embed, and all the solutions I’ve come across are related to ...

Arranging Vue numbers

Vue data contains: data: { offices: requestData, selectedFloors: [ "3", "4", "5", "10", "11", "12", ...

Executing a Particular Function in PHP with Arguments

As a newcomer to PHP and JavaScript, I'm attempting to invoke a specific function in a PHP file from JavaScript. Here is my code: <script> function load($dID) { $.ajax({ url: "myPHP.php", ...

Real-time collaborative Whiteboard using WebSocket technology (socket.io)

I am currently working on developing a collaborative online whiteboard application using HTML5 canvas, Node.js, and Websockets (Socket.io). While my progress is going well, I am facing some challenges when it comes to drawing circles. I have been successfu ...

Error message: CORS policy prevents third-party scripts from running in Next.js

I am encountering an issue with implementing a script handling tool in my Next.js project. I followed the documentation on nextjs.org and utilized the worker (experimental) parameter to enhance the page's performance. However, I am facing a CORS polic ...

Transforming the primary image to the thumbnail image when hovering over it with JSON objects

Currently, I am facing an issue with my single-page web application project that involves using jQuery, JSON Bootstrap. So far, I have successfully created a category page, product selection page, and item page. The problem arises on the item page where ...

How to capture a change event in a dynamically loaded element using JQuery

I am facing an issue with dynamically added rows in my table. Each row contains a select option, and I need to trigger an action when the select is changed. However, since the rows are loaded after the page load, my function does not work as expected. < ...

Updating a database on ASP.NET without the need to refresh the page

We are developing a user-friendly application with ASP.NET MVC that focuses on uploading pictures and rating them. The app includes two voting buttons, "like" and "dislike". https://i.sstatic.net/Z3dp5.png Whenever the like button (green) is clicked, the ...

Ending a timer from a different function in a React component

Currently, I am delving into the world of React and attempting to create a timer component. While I have successfully implemented the start function for my timer, I am now faced with the challenge of stopping the timer using an onclick handler from another ...

populating a multi-dimensional array using a "for" loop in Javascript

It appears that JavaScript is attempting to optimize code, causing unexpected behavior when filling a multidimensional array (largeArr) with changing values from a one-dimensional array (smallArr) within a loop. Take the following code for example: largeA ...

Vue-Select Runs into Issue Generating Choices from an Array

As a novice in the world of Vue and Nuxt JS, I am currently immersed in learning and developing a simple web application with Nuxt JS. One specific challenge I am facing is creating a Vue Select option where I pass an array and have the options represent t ...

Using a module function with Ajax in Drupal 7 when an input is changed

There is a function within my Drupal module that updates the shopping basket. I would like this function to be triggered via Ajax when the quantity in an input field is changed. In this scenario: <a href='/my_module/route/nojs' class='u ...

Modifying tags or categories of a post using a sidebar plugin in WordPress Gutenberg

I am currently working on integrating the functionality to add or delete a post's tag or category using a WordPress Gutenberg sidebar plugin built with React and JavaScript. Despite the lack of detailed resources on how to implement this particular us ...

Retrieving the output of an asynchronous function within another function in JavaScript

I'm facing an issue with the Chrome API functions being asynchronous, making it difficult for me to get their return value. Here's a snippet of code that demonstrates my problem. I'm working with AngularJS. $scope.storageGet = function( ...

What is the process for converting a file to base64 encoding, and then uploading it as a multipart file to a backend API using JavaScript

I am working on a project to create a micro-service that can receive base64 encoded data. However, when attempting to send more than 6 MB of data, I encountered the following error message: The multi-part request contains parameterized data (excluding ...

Showing JSON Array Values in a Table

I have created an array and am attempting to display its values in a table. Initially, my solution only displayed a single value from the array that matched an exact ID. You can see this implementation at (). Entering "jjones" would yield a result. I then ...

What steps are needed to set up app.json to support various connection types for incoming requests, including HTTP?

Within my Expo React Native application, I am encountering issues with fetching data from my Ruby on Rails API due to restrictions on http connections. I have explored various solutions that involve modifying the AndroidManifest.xml in Android and Info.pl ...

Executing NPM commands in a sequential manner

If I have the following npm scripts: "scripts": { "pre-build": "echo \"Welcome\" && exit 1", "build_logic": "start cmd.exe @cmd /k \"yo esri-appbuilder-js:widget && exit 1\"", "post_build": "start C:\ ...

Revealed the previously hidden private variables within the Revealing Module Pattern

I have encountered an issue while implementing the Revealing Module Pattern, as I am struggling to expose a modified private property. var myRevealingModule = (function(){ var name = 'Samantha'; function updateName () { name = ...