uniapp 封装接口调用

1.文件结构


image.png

2.新建request.js,请求工具封装(可以新建个util目录)

import {
    getCache
} from "@/utils/cache.js"

// const baseURL = 'http://localhost:3000'
// const baseURL='http://api.jiaiqi.cn:521'
const baseURL = 'https://autumnfish.cn'
// const baseURL='https://api.klutz.cc'
// const baseURL='https://tree.xingyuncm.cn'
// https://aqueous-retreat-34523.herokuapp.com/

const request = {
    get(url, data) {
        return new Promise((resolve, reject) => {
            uni.request({
                url: baseURL + url,
                data: data,
                header: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
                    'cookie': getCache('COOKIE')
                },
                method: "GET",
                success: (response) => {
                    let res = response.data
                    if (res.code === 200||url=='/check/music') {
                        resolve(res)
                    } else {
                        reject(res)
                        showError(res);
                    }
                },
                fail: (error) => {
                    if (error && error.response) {
                        reject(error.response)
                        showError(error.response);
                    }
                },


            });
        })

    },
    post(url, data) {
        return new Promise((resolve, reject) => {
            uni.request({
                url: baseURL + url,
                data: data,
                header: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                method: "POST",
                success: (response) => {
                    let res = response.data
                    if (res.code === 200) {
                        resolve(res)
                    } else {
                        reject(res)
                        showError(res);

                    }
                },
                fail: (error) => {
                    if (error && error.response) {
                        reject(error.response)
                        showError(error.response);
                    }
                },
            });
        })
    },
}
const showError = error => {
    let errorMsg = ''
    switch (error.code) {
        case 400:
            errorMsg = '请求参数错误'
            break
        case 301:
            errorMsg = '未授权,请登录'
            break
        case 403:
            errorMsg = '跨域拒绝访问'
            break
        case 404:
            errorMsg = '请求地址不存在'
            break
        case 408:
            errorMsg = '请求超时'
            break
        case 500:
            errorMsg = '服务器内部错误'
            break
        case 501:
            errorMsg = '服务未实现'
            break
        case 502:
            errorMsg = '网关错误'
            break
        case 503:
            errorMsg = '服务不可用'
            break
        case 504:
            errorMsg = '网关超时'
            break
        case 505:
            errorMsg = 'HTTP版本不受支持'
            break
        default:
            errorMsg = "请求失败"
            break
    }
    uni.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 3000,
        complete: function() {
            setTimeout(function() {
                uni.hideToast();
            }, 3000);
        }
    });
}

export default request

3.创建模块接口fund.js

import request from '@/utils/request'

/**
 *  歌单 获取歌单分类标签
 *  @return {Array}
 */
export const getSongTagList = (params) => {
    return request.get('/playlist/catlist', params)
}

/**
 *  歌单  所有歌单
 *  @return {Array}
 */
export const getSongList = (params) => {
    return request.get('/top/playlist', params)
}

4.创建接口包index.js

const home=require('./modules/home')
const user=require('./modules/user')
const search=require('./modules/search')
const playList=require('./modules/playList')
const qq=require('./modules/qq')
const songList=require('./modules/songList')
const rankList=require('./modules/rankList')
const singer=require('./modules/singer')

export default{
    ...home,
    ...user,
    ...search,
    ...playList,
    ...qq,
    ...songList,
    ...rankList,
    ...singer
}

5.全局使用main.js导入

// 接口
import api from "@/api/index"
Vue.prototype.$api = api;

6.业务内容使用

methods: {
            async initDaPan() {
                const data = await this.$api.getDaPan()
                console.log(data)
            },
}

7.h5跨域处理mainfest.json加入代码

"h5": {
        "devServer": {
            "port": 8080,
            "disableHostCheck": true,
            "proxy": {
                "/java_api": {
                    "target": "域名1",
                    "changeOrigin": true,
                    "secure": false,
                    "pathRewrite": {
                        "^/java_api": ""
                    }
                },
                "/node_api": {
                    "target": "域名2",
                    "changeOrigin": true,
                    "secure": false,
                    "pathRewrite": {
                        "^/node_api": ""
                    }
                }
            }
        }
    }

推荐阅读更多精彩内容