codingmaster398
codingmaster398

Reputation: 257

Unexpected token o in JSON at position 1, what's wrong?

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

Upvotes: 0

Views: 5265

Answers (1)

Parth Kumar
Parth Kumar

Reputation: 66

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.

Upvotes: 1

Related Questions