How do I make an HTTP request in Javascript?
As a developer, you may need to make HTTP requests to fetch data from an API or send data to a server. In Javascript, you can make HTTP requests using the built-in XMLHttpRequest
object or the newer fetch()
API. In this blog post, we will explore both methods and their differences.
XMLHttpRequest
The XMLHttpRequest
object is a built-in object in Javascript that allows you to make HTTP requests. It has been around for a long time and is supported by all modern browsers. Here's an example of how to make a GET request using XMLHttpRequest
:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed. Status code:', xhr.status);
}
};
xhr.send();
In the above example, we create a new XMLHttpRequest
object and call the open()
method to specify the HTTP method and URL. We then set the onload
event handler to handle the response. Finally, we call the send()
method to send the request.
You can also make POST requests using XMLHttpRequest
. Here's an example:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed. Status code:', xhr.status);
}
};
const data = { name: 'John', age: 30 };
xhr.send(JSON.stringify(data));
In the above example, we set the Content-Type
header to application/json
to indicate that we are sending JSON data in the request body. We then call the send()
method with the JSON data as a string.
fetch()
The fetch()
API is a newer and more modern way of making HTTP requests in Javascript. It is supported by all modern browsers except Internet Explorer. Here's an example of how to make a GET request using fetch()
:
fetch('https://api.example.com/data')
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Request failed. Status code:', response.status);
}
})
.then(data => console.log(data))
.catch(error => console.error(error));
In the above example, we call the fetch()
function with the URL as an argument. We then use the then()
method to handle the response. If the response is successful (i.e. has a status code of 200-299), we call the json()
method to parse the response body as JSON. We then log the JSON data to the console. If the response is not successful, we throw an error.
You can also make POST requests using fetch()
. Here's an example:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Request failed. Status code:', response.status);
}
})
.then(data => console.log(data))
.catch(error => console.error(error));
In the above example, we pass an options object as the second argument to fetch()
. We set the method
property to 'POST'
and the headers
property to an object with the Content-Type
header set to application/json
. We also set the body
property to the JSON data as a string.
Conclusion
In this blog post, we explored two ways of making HTTP requests in Javascript: XMLHttpRequest
and fetch()
. Both methods have their advantages and disadvantages, and which one you choose depends on your specific use case. XMLHttpRequest
is more widely supported but has a more verbose syntax, while fetch()
is more modern and has a simpler syntax but is not supported by Internet Explorer. Regardless of which method you choose, it's important to handle errors and parse the response correctly.
'Development' 카테고리의 다른 글
JPA 개요 (0) | 2023.03.13 |
---|---|
스프링 부트 액추에이터 (0) | 2023.03.13 |
Python에서 HTTP 요청은 어떻게하나요? (0) | 2023.03.13 |
우분투에서 전송을 설정하는 방법. (0) | 2023.03.13 |
MSA에서 DevOps의 역할 : 지속적인 통합 및 배포를 구현하는 방법 (0) | 2023.03.13 |