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',
mode : 'cors',
cache: 'no-cache',
credentials : 'same-origin' ,
headers : {
'Content-Type' : 'application/json'
},
redirect : 'follow',
referrerPolicy : 'no-referrer',
body : JSON.stringify(data)
}
const url = "https://192.168.0.6"
fetch(url,options)
.then(res=>res.json())
.then(data=>{
...
})
.catch(err=>{});
fetch(url,{
method : 'POST',
body : input.files[0]
});
Response
readonly properties
Read Only | Description |
---|
res.ok : boolean | 요청 성공 |
res.headers : Headers | 응답 헤더 |
res.body : ReadableStream | 응답 body |
res.bodyUsed : boolean | body가 사용되었는지 여부 |
res.status : number | 상태코드 |
res.statusText : string | 상태 메시지 |
res.url : URL | 응답 url |
methods
Method | Description |
---|
res.arrayBuffer() : Promise | ArrayBuffer의 Promise 리턴 |
res.blob():Promise | Blob Promise 리턴 |
res.json() : Promise | JSON Promise 리턴 |
res.text() : Promise | 문자열 Promise 리턴 |
res.formData() : Promise | FormData Promise 리턴 |
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')