一、在util文件夹内创建api.js
在api.js文件下分为请求类与上传类
//请求类
const BASE_URL = 'http://127.0.0.1:8080/api'//请求域名
export const myRequest = (options) => {
let headerlist = options.header;
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + options.url,//地址拼接
method: options.method || 'GET',
data: options.data,
header: headerlist || {},
success: (res) => {
resolve(res.data)
},
fail: (err) => {
uni.showToast({
title: '获取失败',
icon: "none"
})
reject(err)
}
})
})
}
//上传类
export const myUploadFile = (options) => {
let headerlist = options.header;
return new Promise((resolve, reject) => {
uni.uploadFile({
url: BASE_URL + options.url,
files: options.files,
filePath: options.filePath,
name: options.name,
formData: options.formData,
header: headerlist || {},
success: (res) => {
console.log(res)
if (res.statusCode == 200) {
var data = JSON.parse(res.data)
resolve(data)
} else {
resolve(res)
}
},
fail: (err) => {
console.log(err)
uni.showToast({
title: '获取失败',
icon: "none"
})
reject(err)
}
})
})
}
二、打开在根目录下的main.js
import {myRequest,myUploadFile} from './util/api.js'; //接口挂载原型链
Vue.prototype.$myRequest = myRequest //请求
Vue.prototype.$myUploadFile = myUploadFile //上传
三、使用
//请求类
async loadNewsList() {
const res = await this.$myRequest({
url: '/recommend-data/get-list-by-type/',
method: 'post',//get请求可去掉
data:{},//所需参数
header: {}//请求头
})
console.log(res)
}
上传类上传参数需要注意,具体查看官方API:UNI上传、下载API
//上传类 如上传单张图片如下
loadNewsList() {
uni.chooseImage({
count: 1, //默认9
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths[0];//选择后的图片本地地址
this.$myUploadFile({
url: '/user/upload-avatar',
header: {},
formData: {},
name: 'file',//图片参数名
filePath: tempFilePaths//图片本地地址
}).then(function(response) {
console.log(response)
}).catch(function(error) {
console.log(error);
});
}
});
}
//上传类 如上传多张图片如下
loadNewsList() {
uni.chooseImage({
count: 9, //默认9
success: (chooseImageRes) => {
var ss = {}
const tempFilePaths = chooseImageRes.tempFilePaths.map(item => (ss.uri = item, ss.name = 'pics', ss));//遍历数组
//最后生成的数组格式如
/*
[{
name:'pics',//上传所需的参数名
uri:''//本地地址
},{
name:'pics',//上传所需的参数名
uri:''//本地地址
}]
*/
this.$myUploadFile({
url: '/user/upload-avatar',
header: {},
formData: {},
}).then(function(response) {
console.log(response)
}).catch(function(error) {
console.log(error);
});
}
});
}
具体查看uni官方API https://uniapp.dcloud.io/api/request/request