小程序ajax请求封装

小程序


1、建basehost.js,配置请求的基础域名

export default {
    doubanBaseHost: "https://douban.uieee.com",
    localBaseHost: "localhost:8080/"
}

2、新建 ajax.js,封装wx.request

import basehost from './basehost.js';
class Base{
	constructor(){}
	//wx.request 封装方法 promise
	request({url, params, method, hideLoading}){
		return new Promise((resolve,reject)=>{
			if(!hideLoading){
				wx.showLoading({
					mask:true,
					title:'加载中...',
				})
			}
			wx.request({
				url: basehost.doubanBaseHost + url,
				data: params,
				method,//post get put delete option
				header:{
					'content-type':'json',
				},
				//成功
				success(res){
					resolve(res.data);
					//if(res.code == 401){}
				},
				//失败
				fail(err){
					reject(err);
				},
				//完成
				complete(){
					wx.hideLoading();
				}
			});
		})
	}
}

export default Base;

3、新建api.js,封装api

import ajax from './ajax.js';
class Api extends ajax{
	constructor(){
		super();
	}
	//热门预告
	filmTeaters(params){
		return this.request({
			method:'GET',
			url:'/v2/movie/in_theaters',
			params,
			//hideLoading: true
		})
	}
}
export default new Api();

4、页面中使用

import Api from './../../utils/api.js'

Page({
	data:{
		theaters:{//热门电影
			list: [],
			total: 0
		}
	},
	onLoad(options){
		Api.filmTeaters({}).then(res=>{
			this.setData({
				theaters:{
					list: res.subjects,
					total: res.total,
				}
			});
			console.log(res);
		})
	}
})

你可能感兴趣的:(小程序)