# @mtjs/ajax

> ajax for axios

Latest version **1.1.1** (published 2022-05-12) · MIT license · 0 weekly downloads

## Install

```sh
npm install @mtjs/ajax
pnpm add @mtjs/ajax
yarn add @mtjs/ajax
bun add @mtjs/ajax
```

## Health

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

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.1 |
| Published | 2022-05-12 |
| First published | 2020-08-17 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 2 |
| Unpacked size | 27.4 KB |
| Known vulnerabilities | 0 (+23 in 1 direct dependencies) |
| Install scripts | no |
| Author | LIUTAO |
| Maintainers | iter, wanpan, aihong |
| Keywords | utils |

## Links

- npm: https://www.npmjs.com/package/@mtjs/ajax
- Repository: https://github.com/git-lt/mtjs
- Homepage: https://github.com/git-lt/mtjs#readme
- Issues: https://github.com/git-lt/mtjs/issues
- npm.io page: https://npm.io/package/@mtjs/ajax

## Dependencies (2)

- [qs](https://npm.io/package/qs.md) ^6.8.0
- [axios](https://npm.io/package/axios.md) ^0.21.1

## Recent versions

- 1.1.1 (latest) — 2022-05-12
- 1.1.0 — 2022-02-14
- 1.0.9 — 2022-01-25
- 1.0.8 — 2022-01-25
- 1.0.7 — 2021-08-26
- 1.0.6 — 2021-08-23
- 1.0.5 — 2021-08-20
- 1.0.4 — 2021-07-15
- 1.0.3 — 2021-07-07
- 1.0.2 — 2021-07-07
- 1.0.1 — 2021-06-30
- 1.0.0 — 2021-06-22
- 0.0.4 — 2021-03-31
- 0.0.3 — 2020-09-01
- 0.0.2 — 2020-08-17

## README

## ajax

对 Axios 进行一定的封装，用于简化接口定义与调用方式，支持 TypeScript

### 安装

```
npm install @mtjs/ajax
```

## 初始化

```js
// ajax.js

import Ajax from "@mtjs/ajax";
import axios from "axios";

axios.defaults.timeout = 60 * 1000;
axios.defaults.baseURL = "https://api.example.com";

// ----------------- 拦截器
// 添加请求拦截器
axios.interceptors.request.use(
  function(config) {
    // 在发送请求之前做些什么，如添加token config.headers['token'] = window.localstorage.getItem('token')
    return config;
  },
  function(error) {
    // 请求异常处理。。。
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  function(response) {
    // 对响应数据做点什么, 如缓存token window.localstorage.getItem('token', response.headers.token)
    // 权限验证。。。
    // 业务异常处理。。。
    // 请求成功判断，返回成功的数据
    return response.data;
  },
  function(error) {
    // 响应异常处理。。。
    return Promise.reject(error);
  }
);

// 全局配置
const createAjax = new Ajax({
  axios: axios,
  // post请求的数据类型
  dataType: "json",
  // get请求时，参数对象的序列化规则，
  // 默认为 params => qs.stringify(params, { indices: false });
  paramsSerializer,
  // 请求类型为 x-www-form-urlencoded 时，body数据的序列化规则，
  // 默认为： (data:any) => qs.stringify(data, { allowDots: true });
  dataSerializer,
  // 根据不同框架来显示和隐藏 Loading
  loading: {
    show: () => {
      Toast.loading();
    },
    hide: () => {
      Toast.clear();
    }
  },
  // 延迟多少ms 显示Loading，默认为260ms，如果请求在260ms内完成，则不显示loading
  loadingDelay: 260,
  // 统一的异常处理 (所有报错都会到这里)，这里的 message 建议PC端使用 Notifycation， H5端使用 Dialog 来显示
  catch: err => {
    alert(err.message);
  }
});

export default createAjax;
```

### 定义 API

```js
// api.js
import createAjax from "./ajax";

const apis = {
  login: "post /login",
  getUser: id => `get /user/${id}`
};

export default createAjax.regist(apis, "/api");
```

### 使用

api.apiName({ data: {}, ...options})

options的配置项(只针对当前请求的配置)

```js
{
  // 默认为false 是否显示loading
  loading: false,
  // 默认为全局配置的 dataType 请求的数据类型
  dataType: 'json',
  // 默认为true, 是否使用全局的异常捕获(全局异常捕获后，会中断promise链，后面的不会执行)
  catchError:true,
  // 请求头
  headers: {},
  // loading 中的提示
  loadingText='加载中',
  // get请求时，参数对象的序列化规则
  paramsSerializer,
  // 请求类型为 x-www-form-urlencoded 时，body数据的序列化规则
  dataSerializer,
  // 默认为0，不缓存 get 请求时，数据缓存过期时间，单位 s，大于0时缓存，
  expires = 0,
  // axios 其它的 options 配置
  ...others
}
```

```js
import api from './api'

//示例1： 使用全局的异常处理，业务中不用处理异常
async login(){
  const data = {userName: 'jack', passwrod: '12111' }
  const res = await api.login({data, loading: true})
  // 默认，catchError 为 true 时，报错后，后面的代码不会执行，
  console.log(res);
}

//示例2：url params中带参数，自定义异常处理
getUser(userId){
  // url带参数的调用方式
  api.getUser(userId)({
    data:{ a: 1},
    loading: true,
    // 自定义异常处理
    catchError: false,
  }).then(res => {
    console.log(res)
  }).catch(err => {
    // 处理异常
    console.log(err)
  })
}
```

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