티스토리 뷰
Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공합니다. Fetch API가 제공하는 전역 fetch() (en-US) 메서드로 네트워크의 리소스를 쉽게 비동기적으로 가져올 수도 있습니다.
fetch('http://example.com/movies.json')
.then((response) => response.json())
.then((data) => console.log(data));
|
cs |
// 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()` 호출에 의해 파싱됨
});
|
cs |
'Client > JavaScript' 카테고리의 다른 글
스크립트 질문 (0) | 2022.11.24 |
---|---|
ES6 사용 HTML 파일에서 include 하는 방법 (0) | 2022.11.24 |
Data Type (자료형) (0) | 2017.03.12 |
변수 (0) | 2017.03.12 |
HTML + JavaScript 작성 방법 (0) | 2017.03.08 |
공지사항
최근에 올라온 글