Categories
JavaScript Answers

How to perform a curl request in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *