超详细小程序的网络请求及简单封装

689 阅读2分钟

激动的心,颤抖的手,一起学习马铃薯。。。是小程序

小程序的网络请求

炒鸡基础,炒鸡详细哦

关键词:wx.request,promise,async,await

在小程序中提供了发起https网络请求的方法wx.request(Object)

在js文件中使用此方法

wx.request({
      url: 'http://localhost:4000/top/playlist/highquality',//请求的接口地址
      method:"get|post|其他",//http请求数据的方式,默认是get
      data:{name:'',id:''},//请求的参数,如name和id
      header:{//请求头设置,根据需要自己设置
        //content-type默认为application/json
        'content-type':"application/x-www-form-urlencoded"
      },
      success(res){//请求成功时的回调函数
        console.log(res);
      },
      fail(msg){
          console.log(msg);//请求失败的回调函数
      }
    })

可能会遇到一个错误 一起跟我做:详情->本地设置->不校验合法域名 轻松搞定 前端请求接口数据的参数和返回结果都很类似,并且会频繁请求,效率很重要的嘛,所以封装原生的网络请求就很必要啦;再者,在回调函数中继续编写代码,如果还有回调那就会很臃肿,容易形成回调地狱,利用promise将异步操作转化为同步就很nice啦

封装wx.request

http.js

const pubUrl = "http://localhost:3000/api"//这是我要请求的数据接口的公共部分
const http = (options) =>{
  return new Promise((resolve,reject) => {
    wx.request({
      url: pubUrl+options.url,
      method:options.method || 'get',
      data:options.data || {},
      header: options.header || {
        'content-type':'application/x-www-form-urlencoded'
      },
      success:resolve,
      fail:reject
    })
  })
}
export default http

api.js (这里主要是对要请求的接口进行了封装,接口会有很多,放在同一个文件中方便管理)

import http from 'http.js' //引入上面封装好的请求方法
// 获取商品的一级分类,不需要参数
const _getTopCate = () => {
  return http({
    url:'/getcate'
  })
}
//获取商品详情,需要传入参数
const _getDetail = (id) => {
  return http({
    url:'/getgoodsinfo',
    data:{
      id
    }
  })
}
// 将方法导出,实现复用
export default{
  _getTopCate,
  _getDetail
  }

具体需要请求数据的页面的js文件,如:index.js

import Api from '../../utils/api.js' //首先要引入封装好的上述api文件,路径根据自己文件的位置
Page({
	data:{
    },
    // 因为请求数据的方法用promise封装,所以需要配合async 和 await 来获取到promise中的数据
    async _getCate(){ //在需要请求接口获取数据的方法中调用api中的方法
      let result = await Api._getTopCate();
      console.log(result);
  	},
 	async _getDetail(){
      let result = await Api._getDetail(1);
      console.log(result)
  	}
})

顺便也看看index.wxml文件吧

<view bindtap="_getCate">获取一级分类</view> //点击会触发上述js中的_getCate()事件,然后调用封装的接口获取到数据
<view bindtap="_getDetail">请求数据商品详情</view>

大功告成!这样就封装好了 image 如有错误,感谢指正

如对您有帮助,感谢点赞评论哦