Sometimes, we want to perform a curl request in JavaScript.
In this article, we’ll look at how to perform a curl request in JavaScript.
How to perform a curl request in JavaScript?
To perform a curl request in JavaScript, we can use the fetch
function.
For instance, we write:
(async () => {
const res = await fetch('https://yesno.wtf/api')
const answer = await res.json()
console.log(answer)
})()
We call fetch
with the URL we want to make the request to to make a GET request.
Then we call res.json
to convert the response body object to JSON.
fetch
and res.json
both return promises so we need to use await
to get the resolved value.
And then we log the result.
Conclusion
To perform a curl request in JavaScript, we can use the fetch
function.