Warning: Trying to access array offset on value of type bool in /mnt/KDJ-SH-SGB-STORAGE-1/kdjayako/public_html/wp-content/plugins/pro-elements/modules/dynamic-tags/tags/post-featured-image.php on line 39

Warning: Trying to access array offset on value of type bool in /mnt/KDJ-SH-SGB-STORAGE-1/kdjayako/public_html/wp-content/plugins/pro-elements/modules/dynamic-tags/tags/post-featured-image.php on line 39

Warning: Trying to access array offset on value of type bool in /mnt/KDJ-SH-SGB-STORAGE-1/kdjayako/public_html/wp-content/plugins/pro-elements/modules/dynamic-tags/tags/post-featured-image.php on line 39

Warning: Trying to access array offset on value of type bool in /mnt/KDJ-SH-SGB-STORAGE-1/kdjayako/public_html/wp-content/plugins/pro-elements/modules/dynamic-tags/tags/post-featured-image.php on line 39

KD Jayakody

Call Us: 076 72 33 595


Warning: Trying to access array offset on value of type bool in /mnt/KDJ-SH-SGB-STORAGE-1/kdjayako/public_html/wp-content/plugins/pro-elements/modules/dynamic-tags/tags/post-featured-image.php on line 39

How do I make HTTP Request in Javascript?

Dec 10, 2022

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.

Recent Posts