본문 바로가기

개발/JavaScript

[JS] jQuery Ajax를 바닐라 JS fetch()로 바꾸기

 

 

 

- jQuery 코드

var main = {
  init: function() {
    var _this = this;
    $('#btn-save').on('click', function() {
      _this.save();
    });
  },
  save: function() {
    var data = {
      title: $('#title').val(),
      author: $('#author').val(),
      content: $('#content').val(),
    };
    
    $.ajax({
      type: 'POST',
      url: '/api/v1/posts',
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(data)
    }).done(function() {
        alert('글이 등록되었습니다.');
        window.location.href = '/';
    }).fail(function(error) {
        alert(JSON.stringify(error));
    });
  }
}
    })

 

 

 

- JavaScript

const saveBtn = document.getElementById("btn-save");
const title = document.getElementById("title");
const author = document.getElementById("author");
const content = document.getElementById("content");

const main = {
    init : function() {
        const _this = this;
        saveBtn.addEventListener("click", (e) => _this.save())
    },
    save : async function() {
        const data = {
            title: title.value,
            author: author.value,
            content: content.value,
        };

        await fetch("/api/v1/posts",
        {
        method: "POST",
        headers: {
            'content-type': 'application/json; charset=utf-8',
            },
        body: JSON.stringify(data),
        })
        .then((data)=> {
        alert("글이 등록되었습니다.");
        window.location.href ='/';})
        .catch((error) => alert(JSON.stringify(error)))
    }
}


main.init();

 

- Ajax -> fetch API

- $() -> document.getElementById()

- on() -> addEventListener()

 

 

* const main 선언한 이유

  • 다른 js에서 init, save function이 있을 경우
    • 브라우저의 스코프는 공용공간이기 때문에 나중에 로딩된 js의 init, save가 먼저 로딩된 js의 function을 덮어쓰게 된다.
    • 협업 시 중복된 함수 이름이 발생할 수 있기 때문에 index.js만의 유효범위(스코프)를 만들어 사용

 

  • main이라는 객체를 만들어 해당 객체에서 필요한 모든 function을 선언하여 다른 js와 겹칠 위험을 없앤다.
    • main 객체 안에서만 function이 유효

 

 


 

 

fetch API

- https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch

- fetch()Promise 객체를 반환

fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));

- option

// POST 메서드 구현 예제
async function postData(url = '', data = {}) {
  // 옵션 기본 값은 *로 강조
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE 등
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json',
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data), // body의 데이터 유형은 반드시 "Content-Type" 헤더와 일치해야 함
  });
  return response.json(); // JSON 응답을 네이티브 JavaScript 객체로 파싱
}

postData('https://example.com/answer', { answer: 42 }).then((data) => {
  console.log(data); // JSON 데이터가 `data.json()` 호출에 의해 파싱됨
});

 

 

 

 

'개발 > JavaScript' 카테고리의 다른 글

[JS] Optional chaining  (0) 2023.03.28
[JS] addEventListener가 동작을 안한다  (0) 2022.09.22
[NestJS] logger, Configuration  (0) 2022.09.02
[NestJS] Unit Testing, End-to-End(E2E)  (0) 2022.08.10
[NestJS] Modules, DI  (0) 2022.08.10