Marcelo
Marcelo

Reputation: 824

Fetch in React Uncaught (in promise)

I'm getting this error on a fetch in React:

Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0

I have already found that the issue is that fetch is adding http://localhost:3000/ to the beginning of the url request and I do not know why.

This is my fetch:

export function getRecipes(ingredients, dish) {
    const url = `www.recipepuppy.com/api/?i=${ingredients}&q=${dish}`;
    console.log(url)
        return dispatch => {
            //dispatch(setRecipesRequest());
            fetch(url, {
                method: 'GET'
            }).then(response => response.json())
              .then(json => {
                  console.log('recipes', json);
                  setRecipes(json);
                });
        }

}

Even though I have specified the url, this is the request URL that the Network tab displays on google chrome:

http://localhost:3000/www.recipepuppy.com/api/?i=asdasd&q=asdasd

And I need it to be:

www.recipepuppy.com/api/?i=asdasd&q=asdasd

Upvotes: 1

Views: 717

Answers (1)

Stephen
Stephen

Reputation: 1099

To define a external request, you need to define the protocol, otherwise it will be relevant to your domain.

Adding http/s to the start of the request should solve your issue

const url = http://www.recipepuppy.com/api/?i=${ingredients}&q=${dish};

Example from MDN: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

Upvotes: 1

Related Questions