-1

I have made a small vanilla javascript code to fetch api but it is throwing the error "Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0". I m not able to understand, exactly why the error is caught. Can somebody help me to resolve this.

const config = {
  url: "https://randomuser.me/",
  numberCards: 24
};

fetch(`${config.url}&amount=${config.numberCards}`)
  .then(function(response) {
    return response.json();
  })
  .then(function(apiResponse) {
    // Output API response to console to view.
    console.log(apiResponse);
  });
Sajjad Tabreez
  • 188
  • 4
  • 21
  • 1
    What is the response you get? – VLAZ Nov 19 '20 at 10:15
  • main.js:7 GET https://randomuser.me/%20&%20amount%20=24 404 (Not Found) and Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0 – Sajjad Tabreez Nov 19 '20 at 10:17
  • Well there you go `Not found` is not valid JSON, so it fails to parse. You need to check if the response actually succeeded first. – VLAZ Nov 19 '20 at 10:19
  • Status: 200 (OK) Time: 42 ms It is actually hitting the API and response is shown.....But whenever I try I get uncaught (in promise) error – Sajjad Tabreez Nov 19 '20 at 10:22
  • 1
    In that case, that API is being stupid and returning a "success" with an error message in it. If the API is under your control, you should change it. If it isn't...I suppose you have to filter out error messages like that one before attempting to parse. – VLAZ Nov 19 '20 at 10:23

1 Answers1

1

It's because of this.

const config = {
  url: "https://randomuser.me/",
  numberCards: 24
};

fetch(`${config.url}&amount=${config.numberCards}`)

It should be,

const config = {
  url: "https://randomuser.me/api/",
  numberCards: 24
};

fetch(`${config.url}?amount=${config.numberCards}`)

It's because the json data are from "https://randomuser.me/api/". Not "https://randomuser.me/". And the query strings must begin with a "?" mark. "&" mark is used to separate query strings. (like this "https://example.com/?amount=24&hi=en")

ChalanaN
  • 407
  • 4
  • 13