uniapp前端ajax教学,uni-app封装ajax请求方法

位置项目根目录index.js

定义了两种请求get和post

import baseconfig from "./common/baseconfig.js"

const httpClient = {

request:function(method,url,data){

var headers={

"Content-Type": "application/x-www-form-urlencoded",

"Auth-Token": uni.getStorageSync("auth_token")

};

return new Promise((resolve,reject)=>{

uni.showLoading({

title:"加载中",

mask:true

});

uni.request({

url:url,

header:headers,

data:data,

method:method,

dataType: 'json',

success:function(res){

uni.hideLoading()

console.log("接口获取原始数据:-------------------",res.data)

if(res.statusCode == 401){

uni.showToast({

icon: 'none',

duration:1000,

title: res.data.error.message

});

setTimeout(function(){

uni.reLaunch({

url: '../login/login'

});

},1500);

}else{

if(res.data.error != null){

uni.showToast({

icon: 'none',

duration:1000,

title: res.data.error.message

});

return;

}else{

resolve(res.data);

}

}

},

fail: function(err){

uni.hideLoading()

reject(err)

}

})

})

},

Get: function(url,data){

let allurl = this.geturl(url);

return this.request('GET',allurl,data)

},

Post: function(url,data){

let allurl = this.geturl(url);

return this.request('POST',allurl,data)

},

geturl:function(url){

return baseconfig.server+url

}

};

module.exports = httpClient

位置common/baseconfig.js

var baseconfig={};

if(process.env.NODE_ENV === 'development'){

baseconfig = {

server:'http://development.test.net'

}

}else if(process.env.NODE_ENV === 'production'){

baseconfig = {

server:'http://production.test.net'

}

}

export default baseconfig;

根目录main.js修改

import {get,post} from ‘./api.js’

Vue.prototype.apiget = get

Vue.prototype.apipost = post

注册后在vue文件可以this.apiget直接调用

import Vue from 'vue'

import App from './App'

import store from './store'

import {get,post} from './api.js'

Vue.prototype.apiget = get

Vue.prototype.apipost = post

Vue.config.productionTip = false

Vue.prototype.$store = store

App.mpType = 'app'

const app = new Vue({

store,

...App

})

app.$mount()

demo.vue  测试案例

methods:{

minfo() {

let that=this

that.apiget('/broker/my/info/dealer',{}).then(res => {

that.dealer = res.dealer

});

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值