uniapp 请求封装

require.js

 

import { cofing } from '../cofing.js'

export async function requestApi(url, data={}, method = "post") {
  let respondData = {msg: "服务异常"};
  try {
    const res = method === "post" ? await request(url, data, 'POST') : await request(url, data)
        if (res.msg) respondData = res;
  } catch (e) {
    console.log(e, 'request_error')
  }
  return respondData;
}

function request(url, data, method='GET') {
    return new Promise((resolve,reject) => {
        uni.request({
            url: cofing.base_url + url,
            header: {
                'content-type': 'application/json',
                // 'token': uni.getStorageSync('token')
            },
            method,
            data,
            success: (res) => {
                if (res.data.error) {
                    resolve(res.data.error)
                } else {
                    resolve(res.data)
                }
            },
            fail: (err) => {
                uni.hideLoading();
                reject(err)
                showError(err.message)
            }
        })
    })
}

function showError(msg) {
    uni.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
    })
}

 

 

 

http.js

import { requestApi } from "./require.js";

//微信小程序登录
export async function wechatMPLogin(data) {
    return await requestApi("/wechatMPLogin", data);
}

cofing.js

let BASE_URL = 'http://dev.xxxxxxay.com/api' //正式
const cofing = {
    base_url: BASE_URL
}
export { cofing }

使用

import { wechatMPLogin } from '@/api/http.js'

async http(){
    let res = await wechatMPLogin({code: loginRes.code})
}

  

posted @ 2022-03-11 18:25  龙卷风吹毁停车场  阅读(466)  评论(0)    收藏  举报