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

@pluve/fetch

v0.9.9

Published

wrap fetch

Downloads

13

Readme

@pluve/fetch

@pluve/fetch 基于 fetch 封装网络请求。在低版本浏览器环境中时注意兼容处理。一般可使用 polyfill-io

安装

npm install @pluve/fetch -S

使用说明

@pluve/fetch 支持自定义请求头,可动态设置鉴权 token,实现了请求和响应结果拦截器,可对响应报文统一处理。支持超时时间配置,debug 模式等。目前仅支持 GET、POST 方式。

setDebug

设置是否为 debug 模式。debug 模式下,控制台会打印详细的接口请求及响应信息,默认为关闭,可在开发测试模式下开启。避免影响性能,建议在生产环境关闭。

import FetchAgent from '@pluve/fetch';
FetchAgent.setDebug(true);

setTimeout

设置超时时间,默认为 15s,单位为毫秒

FetchAgent.setTimeout(15000);

setupDefaultGlobalHeaderGenerator

设置统一请求头信息,若某个接口请求头有特殊要求,可在 GET、POST 方法中设置

FetchAgent.setupDefaultGlobalHeaderGenerator(() => new Object());

setupDefaultCommonReqBodyGenerator

在请求体中设置通用参数,如鉴权信息等

FetchAgent.setupDefaultCommonReqBodyGenerator(() => new Object());

setupReqInterceptor

接口请求拦截器,返回 false 则不拦截请求。

FetchAgent.setupReqInterceptor((req: IRequestParam) => false);

setupRespInterceptor

响应结果拦截器,返回 false 则不拦截响应。可应用 token 过期等场景。

FetchAgent.setupRespInterceptor((response: any) => false);

IRequestParam

请求参数说明

interface IRequestParam {
  url: string; // 接口请求链接
  method?: 'GET' | 'POST'; // 请求参数
  headers?: Headers | {}; // 请求头
  body?: any; // 请求体,通常情况传JSON对象即可,支持application/json 和  application/x-www-form-urlencoded
  submitDataType?: 'json' | 'form'; // 数据提交类型
  timeout?: number; // 超时时间
  [key: string]: any;
}

GET

发送 get 请求,返回 Promise

FetchAgent.get({ url: 'url' }); // // 返回Promise<any>

POST

发送 post 请求,返回 Promise

FetchAgent.post({url, {bodyInfo: 'bodyInfo'}); // 返回Promise<any>

// raw json方式提交
const body = { pageNo: 1, pageSize: 10 };
const headers = { Authorization: `token` };
const params = { url, headers, body, submitDataType: 'json' };
const resp = await FetchAgent.sendPost(params);

// FormData 方式提交
const body = { key: 'value' };
const headers = { Authorization: `token` };
const params = { url, headers, body, submitDataType: 'form' };
const resp = await FetchAgent.sendPost(params);

在 react 中使用示例

/**
 * title: @pluve/fetch
 * order: 2
 * desc: 使用```@pluve/fetch``` 处理网络请求,在vue项目中使用类似.
 **/

import React, { useReducer, useEffect } from 'react';
import { Button } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import FetchAgent from '@pluve/fetch';
import 'antd/dist/antd.css';

interface IFetchProps {
  fetchResult: string;
  loading: boolean;
}

FetchAgent.setDebug(true);

const init = (initialValue: string) => {
  return { fetchResult: initialValue || '请点击发送请求', loading: false };
};

const reducer = (state: IFetchProps, action: { type: 'fetch' | 'reset' | 'loading'; payload: any }) => {
  console.log('action -> ', action);
  switch (action.type) {
    case 'loading':
      return { ...state, ...action.payload };
    case 'fetch':
      return { ...state, fetchResult: action.payload };
    case 'reset':
      return init(action.payload || '请点击发送请求');
    default:
      throw new Error();
  }
};

const fetchData = async dispatch => {
  dispatch({ type: 'loading', payload: { fetchResult: '', loading: true } });
  try {
    const resp = await FetchAgent.get({ url: 'https://xxx.yyy.com/zzz' });
    dispatch({ type: 'fetch', payload: JSON.stringify(resp[0]) });
  } catch (e) {
    console.log('fetchData error: ', e);
    dispatch({ type: 'fetch', payload: `error${e}` });
  } finally {
    dispatch({ type: 'loading', payload: { loading: false } });
  }
};

const SmartFetchDemo: React.FC<IFetchProps> = ({ initialValue }) => {
  const [state, dispatch] = useReducer(reducer, initialValue, init);
  useEffect(() => {
    console.log('state update -> ', state);
    return () => {
      console.log('effect clean up ...');
    };
  }, [state]);
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: '1rem' }}>
        <Button type="primary" onClick={() => fetchData(dispatch)}>
          Fetch
        </Button>
        <Button style={{ marginLeft: '1rem' }} onClick={() => dispatch({ type: 'reset' })}>
          Reset
        </Button>
      </div>
      FetchResult: {state.fetchResult}
      {state.loading ? <LoadingOutlined /> : undefined}
    </>
  );
};

export default SmartFetchDemo;

外部依赖

若低版本浏览器需要依赖 whatwg-fetch

issues 说明

暂无版本计划