1

I'm fetching the API from the system itself inside the blade template view. But I always return {}.

fetch("http://mylaravelapp.com/api/list")
.then(response => {
     console.log(JSON.stringify(response));
});

I already set CORS header inside my API using this library, https://github.com/barryvdh/laravel-cors.

4
  • 1
    did you check on browser network section, did you get the result from server-side? Commented Sep 23, 2019 at 11:42
  • @Gulshan I already tested with POSTMAN, no issue. Commented Sep 23, 2019 at 11:42
  • The fetch promise is axios? I'm asking because you need to set csrf-token so have to be certain that has been set. Commented Sep 23, 2019 at 11:44
  • @SundayJohnson - "The fetch promise is axios?" Not if it's the built-in fetch, no. Commented Sep 23, 2019 at 12:00

2 Answers 2

6

There are a couple of problems:

  1. You're not checking that the HTTP request succeeded. Lots of people make this mistake, it's a flaw in the fetch API design, more here on my anemic little blog. You need to check response.ok.
  2. response is an object with no own, enumerable properties, so JSON.stringify will return "{}" for it. To get the response, you must read the response body via one of the response object's methods, such as text, json, arrayBuffer, formData, or blob.

So for instance:

fetch("http://mylaravelapp.com/api/list")
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    return response.text(); // or .json(), .arrayBuffer(), ...
})
.then(data => {
    console.log(JSON.stringify(data));
})
.catch(error => {
    console.error(error.message);
});
Sign up to request clarification or add additional context in comments.

Comments

-2

Try to return JSON Data and use JSON dataType in your Fetch request

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.