I am getting an error while making fetch request the curl command works fine which is
curl https://quizapi.io/api/v1/questions -G \
-d apiKey=my_key
but when I do a javascript request
fetch("https://quizapi.io/api/v1/questions", {
body: "apiKey=my_key",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
})
.then((res) => res.json())
.then((data) => {
console.log(data);
});
I get an error
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Edit
fetch('https://quizapi.io/api/v1/questions', {
headers: {
'X-Api-Key': `${apiKey}`,
},
})
.then((res) => res.json())
.then((data) => {
console.log(data);
});
You're getting an HTML response (probably a 401 error). According to the API docs, you need to pass the authentication token as the apiKey query parameter or X-Api-Key header.
The -G flag in curl makes it a GET request and passes any data parameters (-d) into the query string. That's where you're going wrong.
You are making a POST request via fetch() and attempting to send the credentials in the request body. That's not going to work.
Try this instead, making a GET request and passing the credentials in the header
fetch("https://quizapi.io/api/v1/questions", {
headers: {
"X-Api-Key": apiKey
},
// the default method is "GET"
}).then(res => {
if (!res.ok) {
throw new Error(res)
}
return res.json()
}).then(console.log).catch(console.error)
The alternative is to include the apiKey in the query string
const params = new URLSearchParams({ apiKey })
fetch(`https://quizapi.io/api/v1/questions?${params}`)