uniapp请求封装(适合小白,简单易懂,直接复制代码就可以用,像我一般懒得写 就直接复制改改就ok了)
1.封装部分
const httpRequest = (opts, data) => { let httpDefaultOpts = { url: baseUrl + opts.url, data: data, method: opts.method, header: opts.method == 'get' ? { 'X-Requested-With': 'XMLHttpRequest', "Accept": "application/json", "Content-Type": "application/json; charset=UTF-8" } : { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, dataType: 'json', } let promise = new Promise(function(resolve, reject) { uni.request(httpDefaultOpts).then( (res) => { resolve(res[1]) } ).catch( (response) => { reject(response) } ) }) return promise }; //带Token请求 const httpTokenRequest = (opts, data) => { let token = ""; uni.getStorage({ key: 'token', success: function(ress) { token = ress.data } }); //此token是登录成功后后台返回保存在storage中的 let httpDefaultOpts = { url: baseUrl1 + opts.url, data: data, method: opts.method, header: opts.method == 'get' ? { 'Token': token, 'X-Requested-With': 'XMLHttpRequest', "Accept": "application/json", "Content-Type": "application/json; charset=UTF-8" } : { 'Token': token, 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, dataType: 'json', } let promise = new Promise(function(resolve, reject) { uni.request(httpDefaultOpts).then( (res) => { resolve(res[1]) } ).catch( (response) => { reject(response) } ) }) return promise }; export default { baseUrl, httpRequest, httpTokenRequest }
2.使用部分
import http from '@/request/request.js';
datas(orderId, that) { let uRl = { url: '/ServiceManager/smOrder/queryOrder.do?authType=show', method: 'post' }; let data = { 'orderId': orderId, //'20200428021003499648265' 'page': 0, 'size': 10 }; http.httpRequest(uRl, data).then(res => { console.log("请求结果res", res) }, error => { console.log(error) }) },