ajax+promise 封装http请求

'use strict';
require('native-promise-only');
module.exports = {
    wrapperRequest: function (type, url, data, isHideLoading) {
        var type = arguments[0], url = arguments[1], data, isHideLoading;

        if(arguments[2] && typeof arguments[2] === 'boolean') {
            isHideLoading = arguments[2];
        } else {
            data = arguments[2];
            isHideLoading = arguments[3];
        }

        var loading = new LoadingService();
        if(!isHideLoading) {
            loading.show();
        }
        var httpIP = global.ENV.remoteHost;
        httpIP = httpIP + '/api/';
        var aUrl = httpIP + url;
        var self = this;
        var promise = new Promise(function(resolve, reject) {
      var httpConfig = {
            type: type,
            contentType: 'application/json',
            url: aUrl,
                dataType: 'json'
        };
        httpConfig.headers = {
            'x-auth-token': 'xxxxxxxx'
        };
        if (data) {
            httpConfig.data = data; 
        }
      httpConfig.success = function(data, textStatus, request) {
            resolve(data);          
      };
      httpConfig.error = function (error) {
        if (error.status == 401) {

                } else {
                    reject(JSON.parse(error.response));
                }
          };
            $.ajax(httpConfig);
        });
        return promise;
    },
    get: function (url, data, isHideLoading) {
        return this.wrapperRequest('GET', url, data, isHideLoading);
    },
    put: function (url, data, isHideLoading) {
        data = JSON.stringify(data);
        return this.wrapperRequest('PUT', url, data, isHideLoading);
    },
    post: function (url, data, isHideLoading) {
        data = JSON.stringify(data);
        return this.wrapperRequest('POST', url, data, isHideLoading);
    },
    delete: function (url, isHideLoading) {
        return this.wrapperRequest('DELETE', url, isHideLoading);
    }
};

//使用
var HttpService = require('http-service');
getHttpData: function(id){
    return HttpService.get('xxx/' +id);
  },

猜你喜欢

转载自blog.csdn.net/bule_chen/article/details/51384224