How do I make an HTTP request in Javascript?
To make an HTTP request in JavaScript, you can use the fetch()
API, which is built into modern browsers. Here's an example:
javascriptfetch('https://example.com/api/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/api/data
and expecting a JSON response. The fetch()
function returns a Promise that resolves with a Response
object. We can then use the json()
method on the Response
object to extract the JSON data.
You can also customize the request by passing additional options to the fetch()
function. For example, to send a POST request with data, you can do:
javascriptfetch('https://example.com/api/data', {
method: 'POST',
body: JSON.stringify({ foo: 'bar' }),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, we're sending a POST request with a JSON payload of { "foo": "bar" }
. We're also setting the Content-Type
header to indicate that the payload is JSON.
Comments
Post a Comment