Uncategorized

How do I make HTTP Request in Javascript?

To make an HTTP request in JavaScript, you can use the fetch() function. Here’s an example of how to use fetch() to send a GET request to an API:

fetch('https://example.com/api/endpoint')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))

In this example, fetch() sends a GET request to the specified URL and returns a Promise that resolves to a Response object. The Response object has a json() method that you can use to parse the response body as JSON and return the parsed data as a JavaScript object.

You can also use the fetch() function to send other types of HTTP requests, such as POST, PUT, and DELETE. To do this, you can pass an optional second argument to fetch() that specifies the request method and any additional request options, such as the request body. Here’s an example of how to use fetch() to send a POST request with a JSON request body:

fetch('https://example.com/api/endpoint', {
method: 'POST',
body: JSON.stringify({
key: 'value'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))

In this example, fetch() sends a POST request to the specified URL with the specified request body and headers. The json() method is used in the same way as in the previous example to parse the response body as JSON and return the parsed data as a JavaScript object.

Related posts
Uncategorized

Installing Odoo 16 on a CentOS 8 Server

Odoo is a powerful open-source business application platform that can be used to manage a wide range…
Read more
Uncategorized

How to Filter Items Inside an Array

To filter and remove objects from an array that have empty values (either null, undefined, or an…
Read more
Uncategorized

5 Tips for Optimizing Your AdSense Earnings

AdSense is a popular ad platform that allows website and blog owners to monetize their traffic by…
Read more
Newsletter
Become a Trendsetter

Sign up for KDJ Guru's Daily Digest and get the best of KDJ Guru Articles, tailored for you.

Leave a Reply

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