微信小程序class封装http

2019-08-25 19:35:43 浏览数 (1)

config.js

代码语言:javascript复制
var config = {
    base_api_url:"https://douban.uieee.com/v2/"
}
export {config}

utils/http.js

代码语言:javascript复制
import {config} from "../config";
class HTTP{
  request(params) {
    if (!params.method) {
      params.method = "GET"
    }
    wx.request({
      url: config.base_api_url   params.url,
      data: params.data,
      method:params.method,
      header: {
        'Content-Type': 'json'
      },
      success: function (res) {
        let statusCode = res.statusCode.toString();
        if(statusCode.startsWith("2")){
          params.success(res.data);
        }else{
          wx.showToast({
            title:"网络错误",
            icon:"none"
          })
        }
      },
      fail: function() {
        wx.showToast({
          title:"错误",
          icon:"none"
        })
      }
    })
  }
}
export{
  HTTP
}

models/movie.js

代码语言:javascript复制
import { HTTP } from "../utils/http";
const movie = "movie/";
class MovieModel extends HTTP {
    getTop250(callback) {
        this.request({
            url: movie   "top250",
            success: res => {
                callback(res);
            }
        })
    }
    getComingsoon(callback) {
        this.request({
            url: movie   "coming_soon",
            success: res => {
                callback(res)
            }
        })
    }
}
export {
    MovieModel
}

index.js 引用

代码语言:javascript复制
import {MovieModel} from "../../models/movie"
var movie = new MovieModel();

0 人点赞