Development

JavaScript에서 HTTP 요청은 어떻게하나요?

sonpro 2023. 3. 13. 14:10
반응형

HTTP request

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.

반응형