fetch, Response, Headers

tapata·2022년 2월 24일
0

JavaScript - Web APIs

목록 보기
2/5

fetch()

  • 네트워크에서 리소스를 가져오는 전역 메서드
  • Promise를 리턴하며, resolve() 되면서 Response를 반환
  • network error 가 발생 할때만 reject() 되며, 404 에러 등 은 then에서 처리
  • fetch(url,options)

e.g. fetch() 메서드로 요청 보내기

  • object를 body에 담아서 보낼때는 JSON.stringify() 메서드로 변환
const data = {
 message : "Good" 
}

const options = {
    method : 'POST',// GET, POST, PUT, DELETE ...
    mode : 'cors', // no-cors, cors, same-origin
    cache: 'no-cache', // default, no-cache, reload, force-cache,
    credentials : 'same-origin' , // include, omit
    headers : {
        'Content-Type' : 'application/json'// 'application/x-www-form-urlencoded', text/plain
    },
    redirect : 'follow', // manual ,follow, error
    referrerPolicy : 'no-referrer', 
    body : JSON.stringify(data)
}

const url = "https://192.168.0.6"

fetch(url,options)
    .then(res=>res.json()) // Response 객체
    .then(data=>{
          ...
    })
    .catch(err=>{});


// 파일을 업로드 하는 경우
// Content-Type은 파일 타입에 의해서 설정
fetch(url,{
    method : 'POST',
    body : input.files[0]
});

Response

  • fetch() 메서드의 응답 객체

readonly properties

Read OnlyDescription
res.ok : boolean요청 성공
res.headers : Headers응답 헤더
res.body : ReadableStream응답 body
res.bodyUsed : booleanbody가 사용되었는지 여부
res.status : number상태코드
res.statusText : string상태 메시지
res.url : URL응답 url

methods

MethodDescription
res.arrayBuffer() : PromiseArrayBuffer의 Promise 리턴
res.blob():PromiseBlob Promise 리턴
res.json() : PromiseJSON Promise 리턴
res.text() : Promise문자열 Promise 리턴
res.formData() : PromiseFormData Promise 리턴

Headers

  • http 통신의 headers

constructors & methods

const content = 'Hello World';
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'text/plain');
myHeaders.set('Content-Length', content.length.toString());
myHeaders.append('X-Custom-Header', 'ProcessThisImmediately');

myHeaders.get('Content-Type')// 'text/plain'
profile
hello

0개의 댓글