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

@rayb/ray-fetch

v3.0.0

Published

ray fetch, httpclient

Downloads

16

Readme

ray-fetch

author

ilex.h

useage

npm install ray-fetch

  • rayfetch

高级使用


// web
import _RayFetch from '@rayb/ray-fetch/lib/rayfetch';

// create instance
const RayFetch = new _RayFetch({
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=utf-8'
  }
});

// 使用
RayFetch.del(url, {params, data}).then(res => res);
RayFetch.get(url, {params, data}).then(res => res);
RayFetch.head(url, {params, data}).then(res => res);
RayFetch.options(url, {params, data}).then(res => res);
RayFetch.post(url, {params, data}).then(res => res);
RayFetch.put(url, {params, data}).then(res => res);

// --- 高级使用 ---

// 1. 统一处理发送数据,用于 sign 校验

const RayFetch2 = new _RayFetch({
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=utf-8'
  },
  beforeSend: ({ url, method, params, data }) => {
    if (method === 'GET'){
      // do someThing
    } else {
      // encode data
    }

    return {
      url, params, data
    };
  }
});

// 2. 自定义子类

class YourFetch extends _RayFetch {
  constructor(){
    super({
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json; charset=utf-8'
      },
      beforeSend: ({ url, method, params, data }) => {
        if (method === 'GET'){
          // do someThing
        } else {
          // encode data
        }

        return {
          url, params, data
        };
      }
    });
  }
}

// 使用
const myFetch = new YourFetch();
myFetch.del(url, {params, data}).then(res => res);
myFetch.get(url, {params, data}).then(res => res);
myFetch.head(url, {params, data}).then(res => res);
myFetch.options(url, {params, data}).then(res => res);
myFetch.post(url, {params, data}).then(res => res);
myFetch.put(url, {params, data}).then(res => res);
  • rayrequest

// web
import rayRequest from '@rayb/ray-fetch/lib/rayrequest';

// DELETE GET HEAD OPTIONS POST PUT

// 使用
rayRequest(url, {
  method: 'POST',
  headers: headers, // 可选
  body: params, // 数据
  reject: function(err){}, // 异常
  timeout: 30000,
  hasCookie: true // 是否携带cookie
});
  • singleFetch

未添加 任何默认 options

// web
import singleFetch from '@rayb/ray-fetch/lib/singleFetch';

// DELETE GET HEAD OPTIONS POST PUT

// single use
singleFetch(url).then(d => console.log(d));
// 处理 success 和 error
singleFetch(url).then(d => {
  // success
  if (d.code>= 200 && d.code < 300>){
    // do success
  } else {
    // do error
  }
});

// 使用
singleFetch(url, {
  method: 'POST',
  headers: headers, // 可选
  body: JSON.stringify(data), // 数据
  reject: function(err){}, // 异常
  timeout: 30000,
  hasCookie: true // 是否携带cookie
});

// 使用自定义 promise 处理 error
function payload(data){
  return new Promise((resolve, reject) => {
    if (data && data.status === 200) {
      resolve(data.result);
    } else {
      if (data && data.message) {
        reject(data.message);
      } else {
        reject(data);
      }
    }
  });
}

singleFetch(url, {
  method: 'POST',
  headers: headers, // 可选
  body: JSON.stringify(data), // 数据
  timeout: 30000,
  hasCookie: true // 是否携带cookie
}).then(payload).then(d => {
  // do success
}, err => {
  // do error
});

check

import { checkStatus, checkJson, checkBlob, checkText, timeoutFetch } from '@rayb/ray-fetch';
// or
// import { checkStatus, checkJson, checkBlob, checkText, timeoutFetch } from '@rayb/ray-fetch/lib/_check';

API

props

|name|type|default| description| |-----|---|--------|----| |opts | object | - | 请求参数 |

rayRequest opts

|name|type|default| description| |-----|---|--------|----| |reject | function | () => {} | 请求失败时回调 | |hasCookie | boolean | undefined | 是否携带cookie | |isFormData | boolean | undefined | 是否是formdata,如果是formdata时,body中的数据将不进行string化,此时需要自行修改headers中的 Content-Typeapplication/x-www-form-urlencoded;charset=utf-8、multipart/form-data),formdata使用MIME参考手册| |headers | object | { Accept: 'application/json','Content-Type': 'application/json; charset=utf-8','X-Api-Key': Store.getCookieByName('X-Api-Key'),'X-Access-Token': ls.read('X-Access-Token'),} | 请求headers | |method | string: DELETE、GET、HEAD、OPTIONS、POST、PUT | GET | 请求方式 | |timeout | number | 30000 | 请求超时,单位 毫秒, 默认 30000毫秒 | |noApiKey | boolean | false | 是否禁用自定添加 X-Api-KeyX-Access-Token headers |

注意,当 isFormData=truebody is FormData 时,默认给 headers 添加 application/x-www-form-urlencoded; charset=UTF-8。由于部分场景存在 boundary 问题,取消默认添加

commonRequest

去除 storage 强依赖,用以适配移动端

fetchEventSource

添加 EventSource 支持

import { fetchEventSource, fes } from '@rayb/ray-fetch/lib/fetchEventSource';

fes({
  url,
  method: 'POST',
  headers,
  body,
  onmessage: (evt) => {},
  onclose: (evt) => {}
});


const controller = new AbortController();
const { signal } = controller;

fetchEventSource(url, {
  signal,
  method,
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({}),
  onmessage,
  onclose
});

注意

使用 rayrequest 进行上传文件时,如果 headers 中的 Content-Type 不支持,需要自行修改。如:

// FormData 模式下,默认不设置 `Content-Type`
headers={
  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}

如果其它 POST|PUT|DELETE 请求,无需默认处理 body,此时,可设置 isFormData=true 将不进行 JSON.stringify 处理,headers 中需要自行处理 'Content-Type'

License

MIT

changelog

  • 20230829 v3.0.0 change to @rayb/ray-fetch and add EventSource
  • 20210319 v2.0.2 update timeout 30000