1、创建一个对象,将该对象挂在Vue的原型下

新建@/common/request.js文件

  1. const webUrl = 'http:/localhost:8082'
  2. export default{
  3. //封装uni.request():
  4. request(options){
  5. options.url = webUrl + options.url
  6. options.method = options.method || this.common.method
  7. options.header = options.header || this.common.header
  8. return new Promise((resolve,reject)=>{
  9. //书写异步操作的代码
  10. uni.request({
  11. ...options,
  12. success:res=>{
  13. if(options.native){
  14. resolve(res) //调取接口后返回的原生数据
  15. }
  16. if(res.statusCode === 200){
  17. resolve(res.data) //异步操作执行成功
  18. }else{
  19. console.log('请求的接口没有找到');
  20. reject(res) //异步操作执行失败
  21. }
  22. }
  23. })
  24. })
  25. },
  26. get(url,data={},options={}){
  27. options.url=url;
  28. options.data=data;
  29. options.method='get';
  30. return this.request(options)
  31. },
  32. post(url,data={},options={}){
  33. options.url=url;
  34. options.data=data;
  35. options.method='post';
  36. return this.request(options)
  37. }
  38. }
  1. const BASE_URL = 'http:/localhost:8082'
  2. export const myRequest = (options)=>{
  3. return new Promise((resolve,reject)=>{
  4. uni.request({
  5. url:BASE_URL+options.url,
  6. method:options.method || 'GET',
  7. data:options.data || {},
  8. success: (res) => {
  9. if(res.data.status !== 0){
  10. return uni.showToast({
  11. title:'获取数据失败'
  12. })
  13. }
  14. resolve(res)
  15. },
  16. fail: (err) => {
  17. uni.showToast({
  18. title:'请求借口失败'
  19. })
  20. reject(err)
  21. }
  22. })
  23. })
  24. }
  1. const baseUrl = 'http:/localhost:8082'
  2. const request = (url = '', data = {}, type = 'GET', header = {
  3. }) => {
  4. return new Promise((resolve, reject) => {
  5. uni.request({
  6. method: type,
  7. url: baseUrl + url,
  8. data: data,
  9. header: header,
  10. dataType: 'json',
  11. }).then((response) => {
  12. setTimeout(function() {
  13. uni.hideLoading();
  14. }, 200);
  15. let [error, res] = response;
  16. resolve(res.data);
  17. }).catch(error => {
  18. let [err, res] = error;
  19. reject(err)
  20. })
  21. });
  22. }
  23. export default request

2、进入main.js文件

  1. import request from '@/common/request.js';
  2. Vue.prototype.$Z = request;

例:在任意文件中书写下列代码可以调用。this.$Z.get();

3、在页面中调用

  1. //封装uni.request():
  2. this.$Z.get('/api/getIndexCarousel.jsp',{},{
  3. native:false
  4. }).then(res=>{
  5. //异步操作成功
  6. console.log(res)
  7. }).catch(res=>{
  8. //异步操作失败
  9. console.log(res)
  10. }).finally(res=>{
  11. //异步操作完成
  12. });
  1. async getPage(){
  2. const res = await this.$Z({
  3. url:'/api/getIndex'
  4. })
  5. this.page = res.data.message
  6. }
  1. getPage(){
  2. this.$Z('/api/news', {
  3. // 传参参数名:参数值,如果没有,就不需要传
  4. }).then(res => {
  5. // 打印调用成功回调
  6. console.log(res)
  7. })
  8. }