微信小程序(四十二)wechat-http拦截器

时间:2024-02-19 09:44:20

注释很详细,直接上代码

上一篇

新增内容:
1.wechat-http请求的封装
2.wechat-http请求的拦截器的用法演示

源码:

utils/http.js

import http from "wechat-http"


//设置全局默认请求地址
http.baseURL = "https://live-api.itheima.net"

//设置响应拦截器
http.intercept.response=(res)=>{
    //返回数据格式(减少一层data)
    return res.data
}

//导出
export default http

app.js

//从utils导入http
import http from './utils/http'

//注册到全局wx实例中
wx.http=http
App({
 globalData:{
     token:''
 }
})

index.js

Page({
  data:{
    list:[]
  },
  //此处就是第四十和四十一篇的结合,抽离出来了网络请求的调用部分进行封装
  //并且设置了响应拦截器对数据进行前提处理
    async onHttp(){
     const res=await wx.http({
        method:'GET',//类型
        url:'/announcement'//设置了基本网站地址就能这么用
      })

      this.setData({//录入数据
        list:res.data
      })
     
    }

  
})

效果演示:

在这里插入图片描述