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:

fetch('http://www.example.com/api/endpoint')
.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: 'johndoe@example.com'
}
fetch(‘http://www.example.com/api/endpoint’, {
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
Follow:
In a world full of worriers, be the warrior.
Leave a comment
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
adbanner