直接上代码
request.js文件
export default {
common: {
baseUrl: "http://172.20.4.212:3000/api",
data: {},
header: {
"Content-Type": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},文章来源地址https://www.toymoban.com/news/detail-487473.html
method: "GET",
dataType: "json"
},
request (options = {}) {
uni.showLoading({
title: '加载中...'
})
options.url = this.common.baseUrl + options.url
options.data = options.data || this.common.data
options.header = options.header || this.common.header
options.method = options.method || this.common.method
options.dataType = options.dataType || this.common.dataType
console.log('option', options)
return new Promise((resolve, reject) => {
uni.request({
...options,
success: (res) => {
if (res.statusCode != 200) {
return reject()
}
setTimeout(() => {
uni.hideLoading()
}, 200)
let data = res.data.data
resolve(data)
},
fail: (error) => {
reject(error)
uni.showToast({
mask: true,
icon: 'error',
title: '接口或网络异常',
duration: 2000
})
}
})文章来源:https://www.toymoban.com/news/detail-487473.html
})
},
/**
* 本地资源上传到开发者服务器
*/
upload (options = {}) {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: options.url,
filePath: options.data.filePath,
name: 'file',
success: (res) => {
resolve(JSON.parse(res.data))
},
fail (error) {
reject(error)
uni.showToast({
mask: true,
icon: 'none',
title: '接口或网络异常',
duration: 2000
})
}
})
})
},
uploadFile (url, data) {
return this.upload({
url,
data
})
},
/**
* get请求
* @param {String} url
* @param {Object} data
*/
get (url, data) {
return this.request({
url,
data,
method: 'GET',
})
},
/**
* post请求
* @param {String} url
* @param {Object} data
*/
post (url, data) {
return this.request({
url,
data,
method: 'POST',
})
},
/**
* put请求
* @param {String} url
* @param {Object} data
*/
put (url, data) {
return this.request({
url,
data,
method: 'PUT'
})
},
/**
* delete请求
* @param {String} url
* @param {Object} data
*/
del (url, data) {
return this.request({
url,
data,
method: 'DELETE'
})
},
}
main.js文件
import App from './App'
import Vue from 'vue'
import './uni.promisify.adaptor'
import http from './utils/request.js'
Vue.prototype.$http = http
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
index.js文件
init () {
this.$http.get('/indexList/data').then(res => {
this.topBar = res.topBar
this.newTopBar = this.initData(res)
}).catch(() => {
uni.showToast({
title: '请求失败',
icon: 'none'
})
})
},
到了这里,关于uni-app封装request请求及get、post、put等方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!