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 web browsers. Here's an example:javascriptfetch('https://example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, fetch
takes a URL as an argument and returns a Promise that resolves to a Response
object. We then call the json()
method on the Response
object to parse the response as JSON, and log the resulting data to the console.
If you need to pass additional options to the fetch
method, such as headers or request method, you can use the second parameter:
javascriptfetch('https://example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John Doe' })
})
.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 containing a name field. We're also setting the Content-Type header to application/json
to tell the server that we're sending JSON data.
Note that the fetch
API only works in modern web browsers. If you need to support older browsers, you may need to use a library like jQuery or Axios to make HTTP requests.
No comments: