ejs,express,mongodb로 토이프로젝트를 하며 ajax와 fetch를 사용중인데, 차이점이 뭐지? 왜 각각 사용하고있었지 난? 이런 생각에 생각정리겸 작성합니다.
https://cocoon1787.tistory.com/756 이곳에서 99%의카피와 1%의 자기 생각을통해 작성한 글입니다.
참고로, form태그로 전송시 새로고침해주지만 ,아래기술들로하면 새로고침이안되고 전송이됨
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { // 요청에 대한 콜백
  if (xhr.readyState === xhr.DONE) { // 요청이 완료되면
    if (xhr.status === 200 || xhr.status === 201) {
      console.log(xhr.responseText);
    } else {
      console.error(xhr.responseText);
    }
  }
};
xhr.open('GET', 'https://localhost:3000'); // 메소드와 주소 설정
xhr.send(); // 요청 전송 
// xhr.abort(); // 전송된 요청 취소var serverAddress = 'https://localhost:3000';
// jQuery의 .get 메소드 사용
$.ajax({
    url: serverAddress,
    type: 'GET',
    success: function onData (data) {
        console.log(data);
    },
    error: function onError (error) {
        console.error(error);
    }
});axios({
  method: 'post',
  url: 'https://localhost:3000/user',
  data: {
    userName: 'Cocoon',
    userId: 'co1234'
  }
}).then((response) => console.log(response));fetch("https://localhost:3000/user/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    id: "asd123",
    description: "hello world",
  }),
}).then((response) => console.log(response));간단한 통신의 경우엔 fetch를 사용하고 기능이 좀 더 필요하다면 axios를 사용하는 게 좋아 보임.
하지만 React-Native와 같이 업데이트가 잦은 경우에는 fetch가 내장 라이브러리이기 때문에 좀 더 안정적일 수도 있겠다고 생각됨.
추가로, fetch는 body폼으로 넘겨줘야함