admin
- March 7, 2023
- Information technology
To make an HTTP request in JavaScript, you can use the built-in fetch()
method, which allows you to send a request to a server and receive a response.
Here’s an example of how to use fetch()
to make a GET request:
fetch('https://example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, we’re sending a GET request to https://example.com/data
, which returns a JSON response. We use the .json()
method to extract the JSON data from the response, and then log it to the console. If there’s an error, we catch it and log it to the console.
Here’s an example of how to use fetch()
to make a POST request:
fetch('https://example.com/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data: 'example' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, we’re sending a POST request to https://example.com/api
, with the JSON data { data: 'example' }
. We’re setting the Content-Type
header to application/json
to indicate that we’re sending JSON data. We use the same pattern as before to extract the JSON data from the response and log it to the console.
You can also use other methods such as PUT, DELETE, PATCH by specifying the method
property to the relevant HTTP verb.