1

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

5
  • 1
    have you tried http:// www. ? Commented May 9, 2018 at 15:16
  • I ll give it a try...1 sec Commented May 9, 2018 at 15:18
  • Genius answer! Thanks a lot Sthepen Commented May 9, 2018 at 15:18
  • no problem, ill add it as the answer :) edit: feel free to mark the answer I provided as correct if you feel its correct. Commented May 9, 2018 at 15:20
  • For sure it is! Commented May 9, 2018 at 15:29

1 Answer 1

1

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);
  });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.