Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

금융을 따라 흐르는 블로그

making an HTTP request in Javascript 본문

카테고리 없음

making an HTTP request in Javascript

DeNarO 2023. 1. 20. 10:30

There are several ways to make an HTTP request in JavaScript, but the most common way is to use the fetch() function, which is a built-in function in modern browsers. Here is an example of how you can use fetch() to make a GET request to an API:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

This code makes a GET request to the JSONPlaceholder API and retrieves data for a specific todo item. The fetch() function returns a promise that resolves with a Response object. In the example above, we chain a .then() function onto the promise to parse the response as JSON and log it to the console. If an error occurs, it will be caught by the catch() block.

Another way to make an HTTP request in JavaScript is by using the XMLHttpRequest object, which is a built-in object in JavaScript that allows you to make HTTP requests. Here is an example of how you can use it:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
xhr.onload = function() {
  if (xhr.status === 200) {
    var data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error(xhr.statusText);
  }
};
xhr.onerror = function() {
  console.error(xhr.statusText);
};
xhr.send();

This code also makes a GET request to the JSONPlaceholder API and retrieves data for a specific todo item. The XMLHttpRequest.open() method is used to open a connection to the specified URL, and the XMLHttpRequest.send() method is used to send the request. The XMLHttpRequest.onload and XMLHttpRequest.onerror properties are used to handle the response and any errors that may occur, respectively.


f