npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mtjs/ajax

v1.1.1

Published

ajax for axios

Downloads

18

Readme

ajax

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

安装

npm install @mtjs/ajax

初始化

// 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

// 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的配置项(只针对当前请求的配置)

{
  // 默认为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
}
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)
  })
}