0

I have been dealing with this for about an hour and can't figure out what's wrong

response = axios.get('https://opentdb.com/api.php?amount=1&type=multiple&encode=url3986').then(function (response) {
        console.log(response.data)
        response=JSON.parse(response.data)
        creator.addQuestion(response.results.question,"quiz",[{answer:response.results.correct_answer.replace("%20"," "),correct:true},{answer:response.results.incorrect_answers[1].replace("%20"," "),correct:false},{answer:response.results.incorrect_answers[2].replace("%20"," "),correct:false}],{answer:response.results.incorrect_answers[3].replace("%20"," "),correct:false})
      
    })

(node:14720) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1

codingmaster398
  • 249
  • 4
  • 14
  • 2
    Welcome to SO! Works fine for me: `fetch(yourURL).then(res => res.json()).then(data => console.log(data))`. If you're trying to parse something that throws a non-JSON token error like this, just print to see what it is your parsing. It's probably already parsed or text that says `"ok"` or something like that. – ggorlen Jan 08 '21 at 02:07
  • 1
    Does this answer your question? [Axios - How to read JSON response?](https://stackoverflow.com/questions/48062821/axios-how-to-read-json-response) – jarmod Jan 08 '21 at 02:10
  • What is the output of `console.log(response.data)`? – Justin Taddei Jan 08 '21 at 02:44

1 Answers1

1

You are fetching data in wrong way. This is the correct way fetching data from api using axios.

response = axios.get('https://opentdb.com/api.php?amount=1&type=multiple&encode=url3986').then((response) => {
   let data =  response.json()
   console.log(data)
}).catch(err => console.log('error occured', err))

You need to use .json() method to parse data.

  • Just went scrolling through my past questions, and found this answer! I didn't think at the time to give you the rep, but now, after 1 year and 3 months, ty – codingmaster398 Mar 19 '22 at 11:35