컴퓨터/Javascript
Javascript fetch
sayyesdoit
2022. 1. 27. 09:41
1. 서버에 데이터 전송하기
1) URL 매개변수
데이터를 URL매개변수에 담아서 보내는 방법이다.
const url = '/example?name=lee&age=30'
fetch(url);
2) text
text 형식의 데이터를 보내는 방법이다. 서버의 req.body에 텍스트가 담겨온다.
const textData = 'Hello, World!';
const url = '/example';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'text/plain'
},
body: textData
});
3) JSON
json 형식의 데이터를 보내는 방법이다. 서버의 req.body에 json이 담겨온다.
const jsonData = {
name: 'lee',
age: 30
};
const url = '/example'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(jsonData)
});
이미 존재하는 form 에서 데이터를 가져와 jsonData를 만들 수도 있다.
const form = document.querySelector('form');
const formData = new FormData(form);
const jsonData = {};
formData.forEach((value, key) => {
jsonData[key] = value;
});
4) FormData
일반 데이터와 파일 데이터를 같이 보내는 방법이다. 서버에서는 multer 와 같은 미들웨어를 사용해야 요청을 받을 수 있다. 일반 데이터는 서버의 req.body 에 담기고, 파일 데이터는 req.file 에 담긴다.
(1) FormData 준비
① 기존 form 에서 가져오기
const form = document.querySelector('form');
const formData = new FormData(form);
② 새로 만들기
const formData = new FormData();
③ 데이터 추가하기
const textData = 'Hello, World!';
const jsonData = { name: 'lee', age: 30 };
const fileData = document.getElementById('file').files[0];
formData.append('message', textData);
formData.append('user', jsonData);
formData.append('file', fileData);
(2) 전송
const url = '/example';
fetch(url, {
method: 'POST',
body: formData
});
5) 기타: x-www-form-urlencoded, XML, protobuf, GrpahQl, SOAP 등이 있지만 특별한 경우가 아니면 쓸 일이 별로 없다.
2. 서버로 부터 응답 받기
fetch 전송하는 부분은 위에 기술했으니 생략한다.
1) 텍스트로 받기
async function fn_fetch () {
const response = await fetch(생략);
const result = await response.text();
}
2) JSON으로 받기
async function fn_fetch () {
const response = await fetch(생략);
const result = await response.json();
}