uniapp配置网络请求

1.简介 

由于平台的限制,小程序项目中不支持 axios,而且原生的 wx.request() API 功能较为简单,不支持拦截器等全局定制的功能。因此,建议在 uni-app 项目中使用 @escook/request-miniprogram 第三方包发起网络数据请求。

官方文档:@escook/request-miniprogram - npm

2.配置步骤

1.在项目根目录下使用npm安装

npm install @escook/request-miniprogram

 如图node_modules下有@escook文件夹则为安装成功

2.在main.js中配置http

// 导入网络请求的包
import { $http } from '@escook/request-miniprogram'

uni.$http = $http

// 请求的根路径
$http.baseUrl = 'https://api-hmugo-web.itheima.net'

// 请求拦截器
$http.beforeRequest = function(options) {
  uni.showLoading({
    title: '数据加载中...'
  })
}

// 响应拦截器
$http.afterRequest = function() {
  uni.hideLoading()
}

3.详解

根据接口要求,一般常用的请求类型为get请求和post请求

res是接口返回的数据,可能包含1.请求结果状态(success)2.数据(data)3.提示(message)

get请求uni.$http.get;post请求uni.$http.post

4.示例

在home.vue中添加获取轮播图方法

扫描二维码关注公众号,回复: 16114758 查看本文章
export default {
  data() {
    return {
      // 1. 轮播图的数据列表,默认为空数组
      swiperList: [],
    }
  },
  onLoad() {
    // 2. 在小程序页面刚加载的时候,调用获取轮播图数据的方法
    this.getSwiperList()
  },
  methods: {
    // 3. 获取轮播图数据的方法
    async getSwiperList() {
      // 3.1 发起请求
      const { data: res } = await uni.$http.get('/api/public/v1/home/swiperdata')
      // 3.2 请求失败
      if (res.meta.status !== 200) {
        return uni.showToast({
          title: '数据请求失败!',
          duration: 1500,
          icon: 'none',
        })
      }
      // 3.3 请求成功,为 data 中的数据赋值
      this.swiperList = res.message
    },
  },
}

get请求返回示例

{
    "message": [
        {
            "image_src": "https://api-ugo-web.itheima.net/pyg/banner1.png",
            "open_type": "navigate",
            "goods_id": 129,
            "navigator_url": "/pages/goods_detail/index?goods_id=129"
        }
    ],
    "meta": {
        "msg": "获取成功",
        "status": 200
    }
}

猜你喜欢

转载自blog.csdn.net/m0_63748493/article/details/126888238
今日推荐