uni-app 接口封装
uni-app 的请求接口在官方文档里是这样的
uni.request({ url: 'https://www.example.com/request', //仅为示例,并非真实接口地址。 data: { text: 'uni.request' }, header: { 'custom-header': 'hello' //自定义请求头信息 }, success: (res) => { console.log(res.data); this.text = 'request success'; } });
在common 中 http.js文档中进行如下封装:
const baseUrl = '****'; //请求地址 const httpRequest = (opts, data) => { let httpDefaultOpts = {
// url: "/dpc/"+opts.url, //本地的重定向接口地址 url: baseUrl+opts.url, //正式环境中接口地址 data: data, beforeSend :function(xmlHttp){ xmlHttp.setRequestHeader("If-Modified-Since","0"); xmlHttp.setRequestHeader("Cache-Control","no-cache"); }, method: opts.method, header: opts.method == 'GET' ? { 'X-Requested-With': 'XMLHttpRequest', "Accept": "application/json", "Content-Type": "application/json; charset=UTF-8" } : { 'content-type': 'application/x-www-form-urlencoded' }, 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 }
在页面main.js中引入http.js
在需要接口请求的部分可以这样写:
http.httpRequest({ url: '/api/mineralInfo', //接口地址 method: 'POST' //请求方式 },{ submitStatus:1 //参数部分 }).then( res => { if(res.data.code == "0"){ //请求成功 } }, error => { console.log('网络请求错误,请稍后重试!'); return; } );
最后一定记得
修改manifest.json 中 h5部分
否则接口会显示302,接口重定向错误。
"devServer" : { "proxy" : { "/dpc" : { "target" : "***", //域名 "changeOrigin" : true, "secure" : false, "pathRewrite" : { "^/dpc" : "" } } }, "https" : false }