封装request.js
import { baseURL} from "./common.js" //接口域名引入 // 拦截 let requestStart = function(params) { // 如果需要在接口参数中加入token,使用下边这段代码 let access_token = uni.getStorageSync("access_token") || ""; if (params.__proto__.constructor.name == "Object") { access_token && (params.access_token = access_token); params = params; } else if (params.__proto__.constructor.name == "FormData") { access_token && (params.append("access_token", access_token)); } // 如果需要显示加载动画 // uni.showNavigationBarLoading(); // 在当前页面显示导航条加载动画。 // uni.showLoading({ // title: "加载中", // mask: true // }); return params; } // 对于 GET 方法,会将数据转换为 query string。例如 { name: "name", age: 18 } 转换后的结果是 name=name&age=18。 // 对于 POST 方法且 header["content-type"] 为 application/json 的数据,会进行 JSON 序列化。 // 对于 POST 方法且 header["content-type"] 为 application/x-www-form-urlencoded 的数据,会将数据转换为 query string。 export function get(url, params = {}) { return new Promise((resolve, reject) => { if (requestStart(params)) { uni.request({ url: baseURL + url, data: params, header: { "content-type": "application/x-www-form-urlencoded;charset=UTF-8" }, method: "GET", success: (res) => { if (res.statusCode != 200)) { uni.showToast({ title: res.statusCode +":"+ res.data.message, mask: true, icon: "none" }); if(res.statusCode == 401){ setTimeout(() => { uni.removeStorageSync("access_token"); uni.removeStorageSync("userinfo"); uni.navigateTo({ url: "/pages/login/login", animationType: "pop-in", animationDuration: 300 }) }, 1500) } }else{ resolve(res.data); if (res.data.code == 0) { uni.showToast({ title: res.data.message, mask: true, icon: "none" }); } } }, fail: (res) => { reject(res) }, }); } }); } export function post(url, params = {}) { return new Promise((resolve, reject) => { // 如果需要在header头中加入token,使用这段代码 header: header, // if(uni.getStorageSync("access_token")){ // header.token = uni.getStorageSync("access_token") // } if (requestStart(params)) { uni.request({ url: baseURL + url, data: params, header: { "content-type": "application/x-www-form-urlencoded;charset=UTF-8" }, method: "POST", success: (res) => { if (res.statusCode != 200)) { uni.showToast({ title: res.statusCode +":"+ res.data.message, mask: true, icon: "none" }); if(res.statusCode == 401){ setTimeout(() => { uni.removeStorageSync("access_token"); uni.removeStorageSync("userinfo"); uni.navigateTo({ url: "/pages/login/login", animationType: "pop-in", animationDuration: 300 }) }, 1500) } }else{ resolve(res.data); if (res.data.code == 0) { uni.showToast({ title: res.data.message, mask: true, icon: "none" }); } } }, fail: (res) => { reject(res) }, }); } }); } var http = { post, get }; export default http;
main.js引入
import http from "@/utils/request.js"; //接口请求封装 Object.assign(Vue.prototype, { "$http": http, })
在页面中使用
onShow(){ this.$http.post("/api/",{ // id:1 }).then(res=>{ if(res.code == 200){ // 成功 }else{ // 失败需要进行的操作 } }) },
总结
到此这篇关于uniapp中uni.request(OBJECT)接口请求封装的文章就介绍到这了,更多相关uniapp uni.request(OBJECT)接口请求封装内容请搜索云海天教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持云海天教程!