[Solved]- React js : Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body in react-admin


We're using the react-admin framework, and I've written a custom DataProvider. I'm attempting to ensure that when a User is created, an instance of UserPossession is also created.

My code snippet below accomplishes this, but the react-admin front-end displays the warning message:

Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have a body

I've checked the Network tab in Developer Tools, and every request to the server is correct; there are no errors. This leaves me confused and stuck because I have no idea what that warning means or why it's occurring.

My code is a part of the convertDataRequestToHTTP constant and looks like this:

        
            if (resource === 'User') {
              url = `${apiUrl}/${resource}`;
              options.body = params.data;
              httpClient(url, {
                method: 'POST',
                body: JSON.stringify(options.body),
              })
              .then(response => (
                url = `${apiUrl}/Location`,
                options.method = 'POST',
                options.body = JSON.stringify({
                   "odata.type": "HardwareDatabase.UserPossession",
                   "Name": response.json.Login,
                   "UserId": response.json.Id
                }),
                httpClient(url, {
                  method: options.method,
                  body: options.body
                })
              ));
            }
        
    

Answer:

Since you mentioned that this code snippet is part of the convertDataRequestToHTTP constant, I can see the issue. httpClient should not be used in this constant as it leads to duplicate API calls or, in your case, triggers this warning. The correct approach would be to define only the options constant.

        
            url = `${apiUrl}/${resource}`;
            options.body = JSON.stringify(params.data);
            options.method = 'POST';
        
    

Later, in the constant responsible for converting the response from OData to the required React Admin format, you should use httpClient.

        
            params.data = {
                "odata.type": "HardwareDatabase.UserPossession",
                "Name": response.json.Login,
                "UserId": response.json.Id
            };
            
            httpClient(`${apiUrl}/Location`, {
                method: 'POST',
                body: JSON.stringify(params.data),
            });