Request fetch for Php api shows all the elements of the request instead of the return json

Asked

Viewed 530 times

0

Hello I have an API that receives parameters and returns a correctly answer in tools like Internet but in my front end I receive all the request and not the response message in the body of the request only if I go in network I can see the answer

const url = http://localhost/heat-maps/client/api_client/Client-Api.php;

        const myInit = { 
            method: 'POST',
            headers: myHeaders,
            body: JSON.stringify(data),
            mode: 'cors',
        };

        const myRequest = new Request(url, myInit);

        fetch(myRequest)
        .then(function(response) {
            return response;
        })
        .then(function(json) {
            console.log(json);
            if (json.status > 200) {
                console.log(json[0].response);
            }

        });

the return response should be :

{
  "response": "Email is already being used in a another acount.Forgot your password go to example.com and reset your password."
}

but my answer is:

Response {type: "basic", url: "http://localhost/heat-maps/client/api_client/Client-Api.php", redirected: false, status: 400, ok: false, …}

someone has gone through something similar that can guide me to find the solution?

  • 1

    Check how the request is in the browser. The answer is in the question itself: your backend is responding with status 400 (bad request). So, the request is probably badly formatted.

  • Edit your question and put the php function that does the Answer.

1 answer

0

speaks guru... I recently went through a similar problem and I managed to get to the following solution;

const url = http://localhost/heat-maps/client/api_client/Client-Api.php;

        const myInit = { 
            method: 'POST',
            headers: myHeaders,
            body: JSON.stringify(data),
            mode: 'cors',
        };

        const myRequest = new Request(url, myInit);

        fetch(myRequest)
        .then(response=>response.json())//veja que a unica alteração foi aqui
        .then(function(json) {
            console.log(json);
            if (json.status > 200) {
                console.log(json[0].response);
            }

        });

Note that you should explicitly say that you want to get your result in the form of an ok JSON.

I hope I helped Hugs....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.