查看: 49|回复: 0

uni-app 接口封装

[复制链接]

3

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2011-1-23
发表于 2020-8-9 17:08:00 | 显示全部楼层 |阅读模式

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
        }

 



来源:https://www.cnblogs.com/yeziyou/p/13463531.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部