限时免费试用:欢迎注册 api.bigmodel.org ,快速体验大模型 API 接入服务。
当前位置:首页 >开发者 >网站框架 >小程序

小程序 | 请求类包装

分类:小程序时间:2018-09-10浏览:2560
//属性层
util/http.js

//基本属性
config.js
```
const config={
  api_base_url:"http://www.wangmingchang.com/v1/",
  appkey:"T********"
}
export {config}//导出
```

函数层
http.js
```
import {config} from '../config.js'
//定义错误
const tips={
  1:'默认错误',
  1005:'appkey错误',
  1007: '网址错误',  
  3000:'该期内容不存在'
}
class HTTP{
  //解构  加上花括号,可通过的对象方式传参
  request({url, method = 'GET', data = {}}){
    return new Promise((resolve,reject)=>{
      this._request(url,resolve,reject,data,method)
    })
  }
  _request(url,resolve,reject,method='GET',data={}){
    
    wx.request({
      url: config.api_base_url+url,
      method:method,
      data:data,
      header:{
        'content-type':'application/json',
        'appkey':config.appkey
      },
      success:(res)=>{
        let code = res.statusCode.toString()
        //es6 新  startsWith 以什么开头   endWith  以什么结尾
        if(code.startsWith('2')){
          // 成功时返回的结果
          resolve(res.data);
        }else{
          //失败时返回
          reject()
          let error_code = res.data.error_code
          this._show_error(error_code)
        }
      },
      fail:(err)=>{
        reject()
        this._show_error(1)
      }
    })
  }
  _show_error(error_code){
    if(!error_code){
      error_code=1
    }
    // console.log(error_code)
    const tip = tips[error_code]

    wx.showToast({
      title:tips?tip:tip[1],
      icon: 'none',
      duration: 1500,
    })

  }
}

export {HTTP};
```

model层
```
import { HTTP } from '../util/http-p.js';

class bookModel extends HTTP{
    getHotList(){
        return this.request({
        url:'book/hot_list'
        })
    }

    getComments(bid) {
      return this.request({
        url: `book/${bid}/short_comment`//es6用法
      })
    }

}

export { bookModel }
```


控制器层
```
//引入
import {bookModel} from '../../model/bookModel.js'
//实例化
const BookModel = new bookModel()


//使用
 onLoad: function (options) {
    const hotList = BookModel.getHotList()
    hotList.then(res=>{
      this.setData({
        books:res
      })
      
    })
  },

```










本站文章如未注明出处均为原创,转载请注明出处,如有侵权请邮件联系站长。
0/500
Share your thoughts respectfully.