JS : XHR HTTP Request

김가영·2021년 2월 23일
0

Web

목록 보기
11/11

GET

const xhr = new XMLHttpRequest();
const url = 'https://api-to-call.com/endpoint';

xhr.responseType = 'json';
xhr.onreadystatechange = () => {
  // check if the request has finished
  if (xhr.readyState === XMLHttpRequest.DONE) {
    return xhr.response
  }
}

// 해당하는 http 와 url 에 대한 request 를 생성한다
xhr.open('GET', url);
xhr.send()

POST


const xhr = new XMLHttpRequest();
const url = 'https://api-to-call.com/endpoint';
const data = JSON.stringify({id:'200'})
xhr.responseType = 'json';

xhr.onreadystatechange = () => {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    // return the response from POST Request
    return xhr.response;
  }
}
xhr.open('POST', url);
xhr.send(data)

// AJAX functions
const shortenUrl = () => {
  const urlToShorten = inputField.value
  const data = JSON.stringify({destination: urlToShorten});
  const xhr = new XMLHttpRequest();
  xhr.responseType = 'json';
  xhr.onreadystatechange = () => {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      renderResponse(xhr.response)
    }
  }
  xhr.open('POST', url);
  xhr.setRequestHeader('Content-type', 'application/json');
  xhr.setRequestHeader('apikey', apiKey);
  xhr.send(data);
}

FETCH

GET

fetch('https://api-to-call.com/endpoint').then((response) => {
  if (response.ok) {
    return response.json();
  }
  throw new Error('Request failed!');
}, networkError => {
  console.log(networkError.message)
}).then(jsonResponse => jsonResponse)

POST

const shortenUrl = () => {
  const urlToShorten = inputField.value;
  const data = JSON.stringify({destination:urlToShorten});
  fetch(url,{
    method: 'POST',
    headers : {
      'Content-type': 'application/json',
      'apikey':apiKey
    },
    body: data
  }).then(response => {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Request failed!');
  }, networkError => {
    console.log(networkError.message)
  }).then(jsonResponse => {
    renderResponse(jsonResponse)
  })
}

async, await

const getData = async () => {
  try {
    const response = await fetch('https://api-to-call.com/endpoint');
    if (response.ok) {
      const jsonResponse = await response.json();
      return jsonResponse;
    }
    throw new Error('Request failed!')
  } catch (error) {
    console.log(error);
  }
}
profile
개발블로그

0개의 댓글