Fetch是浏览器原生提供的对象。用于在 JavaScript 脚本里面发出 HTTP 请求。
XMLHttpRequest 对象因为写起来麻烦,在实际开发中,往往使用它的各种封装库,比如早期的 jQuery。早期的封装库都使用回调函数,很不直观。后来的封装库都改用 Promise 的写法,比如 axios。但是引入jquery、axios等需要加载外部库,而http请求又是一个经常用到的基本需求。所以,内置在浏览器里面的Fetch API就应运而生了。
http://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html
封装fetch
/*** 封装fetch函数,用Promise做回调* @type {{get: (function(*=)), post: (function(*=, *=))}}*/const fetchUtil = {get: (url) => {return new Promise((resolve, reject) => {fetch(url, {method: 'GET',headers: {'Content-Type': 'application/x-www-form-urlencoded',}}).then((response) => response.json()).then(response => {resolve(response);}).catch(err => {reject(new Error(err));});});},post: (url, params) => {return new Promise((resolve, reject) => {fetch(url, {method: 'POST',headers: {'Content-Type': 'application/x-www-form-urlencoded',},body: params}).then((response) => response.json()).then(response => {resolve(response);}).catch(err => {reject(new Error(err));});});}};export default fetchUtil;
使用
import Fetch from "../util/FetchUtil.js";// post请求post(){let params = "";params += "phone=" + "xxxxxx" + "&password="+"123456";Fetch.post("https://carvedu.com/api/user/sms", this.params).then(res => {console.log(res);}).catch(err => {console.log(err);});}// get请求get() {Fetch.get("https://carvedu.com/api/courses").then(res => {console.log(res);}).catch(err => {console.log(err);});}
