src下新建文件夹,api文件夹,api下有config.js 和 list.js

config.js内容


let urlHost = "/"

const service = (params = {}, control) => {
    return new Promise((resolve, reject) => {
        let requestTask = uni.request({
            url: urlHost + params?.url,
            data: params?.data || {},
            header: params?.header,
            method: params?.method || "GET",
            success: res => {
                resolve(res)
            },
            fail: err => {
                reject(err)
            }
        })
        if (control) control(requestTask)

    })
}

//--------------------------base post get function start ---------------------
export function basePostFun(url, data, control, token = "") {
    let params = {
        url: url,
        method: "POST",
        data,
        token,
        header:{
            SessionId: token,
            "Content-Type":  "application/x-www-form-urlencoded"
        },
    }
    return new Promise((resolve, reject) => {
        service(params, control).then(
            res => {
                let data = res.data
                if (data.status === 200) resolve(data)
                else reject(data)
            },
            err => reject(err),
        )
    })
}

export function baseGetFun(url, data, control, token = "") {
    let params = {
        url,
        data,
        token,
        header:{
            SessionId: token,
        },
    }

    return new Promise((resolve, reject) => {
        service(params, control).then(
            res => {
                let data = res.data
                if (data.status === 200) resolve(data)
                else reject(data)
            },
            err => reject(err),
        )
    })
}


//--------------------------base post get function end ---------------------

list.js内容 

import { basePostFun } from "./config.js"

export  function testPost(data,control) {
    return basePostFun("user/login",data,control)
}

export default {
	testPost
}

main.js中引入,配置到全局

import apiList from 'api/list.js'
Vue.prototype.$api = apiList

 使用

login() {
      this.$api.testPost({usr:this.usr,pwd:this.pwd}).then(
        data=>{
          console.log("请求成功",data);
        },
        err=>{
          console.log("请求失败",err);
        }
      )
    },

如果要控制请求的取消可以这样

login() {
      let requestTask = null
      this.$api.testPost({usr:this.usr,pwd:this.pwd},v=>requestTask=v).then(
        data=>{
          console.log("请求成功",data);
        },
        err=>{
          console.log("请求失败",err);
        }
      )
      // 中间遇到一些其它相取消请求,可以这样中断请求任务
      requestTask.abort();
      
    },

解决manifest.json配置h5的请求跨域问题 

 后面加上这一段

"h5": {
		"devServer": {
		  "proxy": {
			"/": {
			  "pathRewrite": {
				"^/": ""
			  },
			  "target": "http://127.0.0.1:5665"/*为服务器的地址*/
			}
		  }
		},
		"publicPath": "./"
	  }

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐