How to perform a curl request in JavaScript?

Estimated read time 2 min read

In JavaScript, you can perform a HTTP request similar to a curl command by using the built-in fetch() method or a third-party library like axios. Here are examples of how to use both methods to perform a GET request:

Using fetch():

fetch('https://example.com/data')
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(error => console.log(error));

In this example, the fetch() method is used to perform a GET request to https://example.com/data. The resulting response is then converted to a text format using the .text() method, and the resulting data is logged to the console. If an error occurs, it is caught and logged to the console.

Using axios:

axios.get('https://example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

In this example, the axios.get() method is used to perform a GET request to https://example.com/data. The resulting response is then accessed using the .data property of the response object, and the resulting data is logged to the console. If an error occurs, it is caught and logged to the console.

Both methods can be used to perform other types of HTTP requests as well, such as POST or PUT requests, by passing additional parameters to the function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply