2

I'm trying to make graphql calls from a React component to a PHP server, using fetch. It is the first time I try using fetch.

I'm using React JS on browser side and Symfony 4 on server side. However all of my calls end up with an empty body on server side, even though my browser dev tools seem to indicate data is sent.

When using graphiql, the requests succeed. I'm trying as much as possible to mimic the graphiql request from React, but the body is always blank.

Here is the 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);
});

I have tried with mode set to cors, no-cors, same-origin, navigate: none of these work.

I have tried with Firefox and Chrome: still no luck.

Changing the content type to application/graphql does not seem to work either.

I have seen many questions dealing with empty bodies in both responses and requests when using fetch, on stackoverflow and elsewhere, but none of the found solutions seem to solve to my case.

I also tried the following, much cruder call, to no avail. It seems I just cannot use fetch at all for a reason I cannot explain:

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

What to do? Am I missing something simple here?

Zephyr
  • 1,598
  • 11
  • 22
  • Your symfony4 backend, does it expect json body or form-encoded post message? I had a [similar issue](https://stackoverflow.com/a/33128994/457268) with an empty body when trying to request a silex (aka symfony light) server. – k0pernikus Jan 16 '18 at 09:36
  • I read the request from the entry point `index.php`, Symfony does not yet expect any specific format at this point, yet the body is still empty. – Zephyr Jan 16 '18 at 09:46
  • 'test=test' would not work if your server is not expecting a parameter called test. the values should match the properties of the class that the endpoint expects – Liam Kenneth Jan 16 '18 at 09:46
  • Possible duplicate of [Fetch in react native not send the post](https://stackoverflow.com/questions/40768352/fetch-in-react-native-not-send-the-post) – Martijn Apr 29 '18 at 13:37

2 Answers2

0

Make sure you're sending Content-Type and Accept headers properly.

'Accept': 'application/json',
'Content-Type': 'application/json', 
Anurag Bhagsain
  • 363
  • 3
  • 10
-1

I now use GraphQL in conjunction with React instead of using fetch directly, and mostly it works pretty well.

Zephyr
  • 1,598
  • 11
  • 22