Fetch API是XMLHttpRequest的升级版,浏览器原生提供,用于发送HTTP请求,属于HTML5新增的API。
参数说明:
| |
| const response = await fetch(url, { |
| method: "GET", |
| headers: { |
| "Content-Type": "text/plain;charset=UTF-8" |
| }, |
| body: undefined, |
| referrer: "about:client", |
| referrerPolicy: "no-referrer-when-downgrade", |
| mode: "cors", |
| credentials: "same-origin", |
| cache: "default", |
| redirect: "follow", |
| integrity: "", |
| keepalive: false, |
| signal: undefined, |
| }) |
复制
GET请求:
| |
| fetch('http://example.com/userInfo?uid=1') |
| .then((response) => { |
| return response.json(); |
| }) |
| .then((e) => { |
| console.log(e); |
| }); |
| |
| |
| const response = await fetch("http://example.com/userInfo?uid=1"); |
| console.log(await response.json()); |
复制
POST请求:
| |
| fetch(url, { |
| method: 'POST', |
| headers: { |
| 'Content-Type': 'application/json;charset=utf-8' |
| }, |
| body: JSON.stringify(jsonData) |
| }) |
| .then(response => { |
| return response.json() |
| }) |
| .then(e => { |
| console.log(e) |
| }) |
| .catch(err => { |
| console.error(err) |
| }) |
复制
响应处理:
1、通过Response对象的状态码判断状态:
| const res = await fetch(url) |
| if (res.status >= 200 && res.status < 300) { |
| return await res.text() |
| } |
| else { |
| return new Error(res.statusText) |
| } |
复制
2、通过Response对象的ok参数判断(对应状态码200-299)
| |
| const res = await fetch(url) |
| if (res.ok) { |
| return await res.text() |
| } |
| else { |
| return new Error(res.statusText) |
| } |
复制
3、读取返回内容
| |
| const res = awati fetch(url, { |
| headers: { |
| "Content-Type": "text/plain;charset=UTF-8" |
| } |
| }) |
| |
| if(res.headers.get("content-type") === 'text/plain') { |
| return await res.text() |
| } |
| |
| if(res.headers.get("content-type") === 'application/json') { |
| return await res.json() |
| } |
复制