1.src文件夹下创建util文件夹
2.util文件夹下创建fetch.js文件
3.fetch.js书写 注意请求的地址 和 请求头 token
import { Toast } from ‘vant’;
//允许同时存在多个 Toast
Toast.allowMultiple();
let dataurl = ‘www.baidu.com’ //我们请求的接口
const Http = function () {
let DeviceID = localStorage.DeviceID;
if (!DeviceID) {
localStorage.DeviceID = DeviceID;
}
this.DeviceID = DeviceID;
};
Http.prototype.fetch = function (url, method, params = {}) {
url = dataurl + url;
let config = { method: method, mode: ‘cors’ };//, mode: ‘cors’
//判断是否为wx内置浏览器
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == “micromessenger”) {
config.headers = {
DeviceType: ‘WXH5’,
DeviceID: this.DeviceID,
};
}
else {
config.headers = {
DeviceType: ‘H5’,
DeviceID: this.DeviceID
};
}
//请求loading
Toast.loading({
message:“加载中”,
className: ‘toast-loading’
});
if (params instanceof FormData) {
config.body = params;
} else {
if (method == ‘get’ || method == ‘head’) {
if (url.indexOf(’?’) > 0) {
url += ‘&’;
} else {
url += ‘?’;
}
for (let key in params) {
url += key + ‘=’ + params[key] + ‘&’;
}
} else {
config.body = JSON.stringify(params);
}
config.headers[‘Content-Type’] = ‘application/json’
}
// 在本地存储中 获取token 存放在 headers头中 注意名字
if (sessionStorage.user) {
let token =JSON.parse(sessionStorage.user)
config.headers.Authorization = 'Bearer ’ + token.remember_token;
}
//对fetch的二次封装
return new Promise((resolve, reject) => {
fetch(url, config).then(async res => {
Toast.clear();
if (res.status == 200) {
let data = await res.json();
if (data.code == 200) {
resolve(data.data || data);
} else {
if (data.code == 202) {
} else if (data.code == 203) {
resolve(data);
} else {
Toast({
message: data.msg,
duration: 1000,
forbidClick: true
});
}
}
} else {
reject(res.statusText);
}
});
});
};
//对fetch的方法封装
Http.prototype.get = function (url, params) {
return this.fetch(url, ‘get’, params);
};
Http.prototype.post = function (url, params) {
return this.fetch(url, ‘post’, params);
};
Http.prototype.put = function (url, params) {
return this.fetch(url, ‘put’, params);
};
Http.prototype.delete = function (url, params) {
return this.fetch(url, ‘delete’, params);
};
export default new Http();
4.util文件夹同级下创建http.js文件
5.http.js内容
import Fetch from ‘…/util/fetch’
export const 名字 = (data) => Fetch.get(‘我们要拼接的地址’,data) //data存放数据 也可以?进行拼接
6.需要的页面进行引入
import { 名字 } from “…/…/util/http”; //这里注意路径
1
7.请求接口
async gettingData() {
await 名字({data的参数}).then((res) => {
console.log(res);
//res 就是我们请求到的数据
});
},
//我们使用了 axync await
// 注意:使用fetch 返回的数据没有status 状态,只有数据