微信小程序模拟axios封装

http.js

const baseURL = "地址"

/**
 * 对于网络请求,设置参数默认值
 */
const DEFAULT_REQUEST_OPTIONS = {
  baseURL,
  timeout:1000*5,
	header: { 
    "Content-Type": "application/json",
    // 'x-token': 'x-token'  // token 看自己是否需要
  },
}

/**
 * 请求的封装
 * @param {String} url 请求的接口地址
 * @param {String} method 请求的方法
 * @param {Object} data 请求的参数
 * @param {Object} option 请求头的配置
 */
const request = (url, method='GET', data={}, option={}) => {

  wx.showLoading({
    title: '加载中...',
  });

  // 合并配置,在配置信息中提取需要的部分
  let { baseURL, header} = Object.assign({}, DEFAULT_REQUEST_OPTIONS, option)
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseURL + url,
      data,
      header,
      method,
      success: res => {
        // console.log('响应:',res);
        wx.hideLoading()
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          resolve(res.data)
        } else {
          //其它错误,提示用户错误信息
          console.error(res);
          resolve(res)
          if(res.statusCode == 404){
            wx.showToast({
              title: '数据不存在',
              icon:'none'
            })
          }
        }
      },
      fail: res => {
        console.error(res);
        wx.hideLoading()
        reject(res)
      }
    })
  })
}



/**
 * GET请求
 * @param {String} url 请求接口地址
 * @param {Object} data 请求参数
 * @param {Object} option 请求头的配置
 */
export const getApi = (url, data, option) => request(url, 'GET', data, option);

/**
 * POST请求
 * @param {String} url 请求接口地址
 * @param {Object} data 请求参数
 * @param {Object} option 请求头的配置
 */
export const postApi = (url, data, option) => request(url, 'POST', data, option);

api.js

import {getApi,postApi } from './http';


export const getBanner = () => getApi("");  

export const getProduct = (data) => getApi("/product/",data);  
 
export const getDetail = (id) => getApi(`/product/${id}/`)

export const postLogin = (params) => postApi("/my_user/login/",params)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值