Javascript
JS : Form 데이터 전송 방식(라이브러리X) + REST API
죽이죽이
2024. 1. 31. 19:05
- Form 데이터 전송 방식
※ new Form() 객체 사용
const form = document.querySelector('#form') const formData = new FormData(form); fetch('/submit', { method: 'POST', body: formData });
※ form 태그의 action, method 속성 사용
<form action="/submit" method="post"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="Submit" /> </form>※ 자바스크립트 객체 사용
const formData = { username: 'daniel', password: 'password' }; fetch('/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) });
- REST API
※ 데이터 생성 (POST)
const form = document.querySelector('#form') const formData = new FormData(form); fetch('/submit', { method: 'POST', body: formData });
※ 데이터 조회 (GET)
// 조회 시에는 method를 GET으로 명시해줄 필요 X const fetchList = async () => { const accessToken = window.localStorage.getItem("token"); const datas = await fetch("/items", { headers: { Authorization: `Bearer ${accessToken}`, }, }).then((res) => res.json()); };※ 데이터 업데이트 (PUT)
const form = document.querySelector('#form') const formData = new FormData(form); fetch('/submit', { method: 'PUT', body: formData });
※ 데이터 삭제 (DELETE)
const userId = 123; fetch(`/submit/${userId}`, { method: 'DELETE', });
