How do I make an HTTP request in Javascript?

Kariuki Maina
By Kariuki Maina 2 Min Read

To make an HTTP request in Javascript, you can use the XMLHttpRequest object or the more modern fetch() function. Here is an example of how to use fetch() to make a GET request to a server:

.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))

In this example, fetch() is used to send a GET request to the specified URL. The response from the server is parsed as JSON and logged to the console. If an error occurs, it is caught and logged to the console as well.

If you want to make a POST request instead of a GET request, you can specify the request method and any request body data in the fetch() options:

const data = {
name: 'John Doe',
email: ''
fetch(‘’, {
method: ‘POST’,
body: JSON.stringify(data),
headers: {
‘Content-Type’: ‘application/json’
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))

- Advertisement -

In this example, a POST request is sent to the specified URL with the request body containing a JSON-encoded string of data. The Content-Type header is set to application/json to indicate that the body of the request is in JSON format. The response from the server is parsed as JSON and logged to the console, and any errors are caught and logged as well.

Share this Article
By Kariuki Maina Kariuki Maina
In a world full of worriers, be the warrior.
Leave a comment
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x