# pa-ajax

> ``` npm install --save-dev pa-ajax ``` ## 2.Usage ### 2-1.在项目中src目录下建立一个配置文件夹如ajaxInject

Latest version **1.0.1** (published 2019-10-16) · ISC license · 0 weekly downloads

## Install

```sh
npm install pa-ajax
pnpm add pa-ajax
yarn add pa-ajax
bun add pa-ajax
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.1 |
| Published | 2019-10-16 |
| First published | 2019-10-16 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 315.9 KB |
| Known vulnerabilities | 0 (+25 in 1 direct dependencies) |
| Install scripts | no |
| Maintainers | tinyfish |

## Links

- npm: https://www.npmjs.com/package/pa-ajax
- npm.io page: https://npm.io/package/pa-ajax

## Dependencies (1)

- [axios](https://npm.io/package/axios.md) ^0.19.0

## Recent versions

- 1.0.1 (latest) — 2019-10-16

## README

# ajax 统一封装

## 1.Installation
```
npm install --save-dev pa-ajax
```
## 2.Usage
### 2-1.在项目中src目录下建立一个配置文件夹如ajaxInject

> 里面分别建一个index.js(入口文件)、ajaxConfig.js(ajax统一配置)、urlConfig.js(接口配置文件)

###### 具体配置演示：

> a.index.js(入口文件)

```
import api from 'pa-ajax'
import ajaxConfig from './ajaxConfig.js' // ajaxConfig为ajax接口配置
import Vue from 'vue'
Vue.prototype.$http = api(ajaxConfig) // 挂载到vue原型下面
```
> b.ajaxConfig.js(ajax统一配置)

```
// import encrypt from './encrypt'
import urlConfig from './urlConfig'
let defaultOptions = {
  method: 'POST', // 默认ajax请求方法
  timeout: 5000, // 默认请求超时时间
  isLoading: true, // 是否展示loading（请求转圈加载动画），默认为true
  limitLoadingTime: 3000, // 接口请求在xxms内完成则不展示loading
  isShowDefaultErrTip: true, // 是否展示接口默认错误提示 如果设为false请在请求的catch里面单独设置提示（如果是某个接口不展示，可在请求传参里面添加）
  requestSucKey: 'resultCode', // 接口请求成功返回的key值  默认为resultCode
  requestSucCode: '0', // 接口请求成功的成功码 默认为0
  requestErrDescKey: 'errorDesc', // 接口请求失败错误描述key值  默认为errorDesc
  urlConfig, // url配置
  headers: {
    'Content-Type': 'application/json;charset=UTF-8' // 统一设置默认请求头，单个接口可以额外配置请求头
  }, // 设置请求headers
  interceptorsRequestFn: [(config) => {
    // Do something before request is sent
    console.log('ajax-sender-data', config['data'])
    // isEncryptPostData && !(encryptExcludePaths || []).includes(config['url']) && (config['data'] = encryptPostData(config['data'])) // 报文加密
    return config
  }, (err) => {
    return Promise.reject(err)
  }], // 统一请求拦截
  interceptorsResponseFn: [(response) => {
    return response.data
  }, (err) => {
    return Promise.reject(err)
  }], // 统一响应拦截
  toastConfig: { // 使用ajax提供的默认消息提示及加载动画
    /**
     * 消息展示默认配置
     */
    msgTipDefault: {
      text: '',
      duration: 2500
    },
    /**
     * 加载动画默认配置
    */
    loadingDefault: {
      loading: true,
      text: 'loading...'
    }
  },
  toastConfig: { // 消息提示配置 (使用自定义消息提示和加载动画)
    /**
     * 请求失败/异常的消息提示框
     */
    msgTip: function (tip) {
      let config$toast = (tips) => {
        const options = {
          type: 'text',
          duration: 2000,
          message: tips,
          position: 'bottom'
        }
        return Vue.prototype.$toast(options)
      }
      return config$toast(tip)
    },
    /**
     * 加载展示
     */
    loading: function () {
      return Vue.prototype.$toast.loading({
        mask: true,
        message: '加载中...'
      })
    },
    /**
     * 清除消息展示框、加载动画
     */
    clear: function () {
      return Vue.prototype.$toast.clear()
    }
  }
}

export default defaultOptions

```

>c.urlConfig.js(接口配置文件)

```
const prefix = '/ts-api1'
const prefix2 = '/ts-api2'
export default {
  mchtInfoList: {
    url: `${prefix}/unionPay/activity/mcht_info_list`,
    method: 'post' // 默认请求方法配置为post的时候可省略此处
  },
  tsRestful: { // restful风格请求
    url: `${prefix2}/getCategories/{cage}`,
    method: 'GET'
  }
}
```


### 2-2.在项目入口文件(如main.js)引入

```
import '@/common/ajax/ajaxInject'
```

### 2-3.例子引用

```
export default {
  created () {
    this.tsAjax()
  },
  methods: {
    async tsAjax () {
      try {
        const sendData = {
          data: {
            a: 123
          },
          headers: {
            'aa': '456'
          }, // 设置请求headers
          isShowDefaultErrTip: false // 是否展示接口默认错误提示 如果设为false请在请求的catch里面单独设置提示
        }
        await this.$http('goodsDetail', sendData)
      } catch (e) {
        console.log('tsAjaxErr', e)
      }
    }
  }
}
```

## 其他说明

> 针对大型项目，urlConfig很大，建议按模块分开写，最后统一合并引入

如：
urlConfig下面建三个文件index.js（统一入口，用来统一合并不同模块请求连接）、goods-config.js（商品模块接口）、pay-config.js（支付模块接口）
```
// goods-config.js

export default {
  goodsDetail: { // 获取商品详情
    url: 'goods/detail/{id}'
  },
  goodsPriceSpc: { // 获取商品规格
    url: 'goods/priceSpc'
  }
}

// pay-config.js

export default {
  payList: { // 获取支付列表
    url: 'pay/payList'
  }
}


/**
 * 获取文件夹下面的请求接口集合
 * modulesContext = require.context('./', true, /-config\.js/)
 */
const getTotalModule = (modulesContext) => {
  let totalModules = modulesContext.keys().reduce((modules, key) => {
    modules[key.replace(/(^\.\/)|(\.js$)/g, '')] = modulesContext(key).default
    return modules
  }, {})
  let obj = {}
  for (let key in totalModules) {
    obj = { ...obj, ...totalModules[key] }
  }
  return obj
}

const prefix = 'ts-api/'
const modulesContext = require.context('./', true, /-config\.js/)
let totalModule = getTotalModule(modulesContext)
// prefix拼接
for (let key in totalModule) {
  totalModule[key].url = `${prefix}${totalModule[key].url}`
}
export default totalModule

```

---
_Source: https://npm.io/package/pa-ajax · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
