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 🙏

© 2025 – Pkg Stats / Ryan Hefner

ssyy-be-request

v0.0.2

Published

request for be cs

Downloads

11

Readme

be-request

基于 axios,为中后台提供前后端通信方案
特点:

  • 用法与 axios 保持一致
  • 默认配置,开箱即用
  • 支持自定义配置,扩展性好
  • 集成测试,可测可控

快速开始

安装

$ npm install @luna/be-request --registry=http://registry.npm.lu-fe.com
or
$ npm add @luna/be-request --registry=http://registry.npm.lu-fe.com

配置 baseURL

// ice.config.js
module.exports = {
  chainWebpack: (config) => {
    config
      .plugin('DefinePlugin')
      .tap(([options]) => {
        return [{
          ...options,
          BASEURL: JSON.stringify('/bpi-be-cs-app/service'),
        }];
      });
   },
}

or

// index.js 程序入口
import request from '@luna/be-request';

request.setConfigs({
   baseURL: '/bpi-be-cs-app/service'
});

使用

// class 组件
import request from '@luna/be-request';

 onGetTableList = async () => {
    try {
      const {list} = await request.post('/customer/get-basic-info', { id: 12 }); // 不用加判断,只有code === '0' || code === '0000'才会到这里
      this.setState({tableList: list || [] })
    } catch (error) {
      error.hideError(); // 如果想用
    }
  }

or

// function 组件 hooks
import {useRequest} from '@luna/be-request';

const [tablelist, requestTablelist]  = useRequest({method: 'post', url: '/post'});

async function handleSubmit() {
    try {
      await requestTablelist();
    } catch (err) {
      console.error(err);
    }
}

关于配置

默认如下配置: 若系统存在差异,可以通过 setConfigs 方法配置,全局生效

const defaultConfigs = {
  baseURL: BASEURL || '/wmc-be-iadmin-app/service', // BASEURL webpack definePlugin 定义
  timeout: 6000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'X-LUFAX-LOCALE': locale.replace('-', '_'),
  },

  luRootUrl: window.mock || `${protocol}//${hostName}${port ? ':' : ''}${port}/api`, // fullUrl = luRootUrl(luRootUrlMedia) + baseURL + url
  luRootUrlMedia: window.mock || `${protocol}//${hostNameMedia}${port ? ':' : ''}${port}/wmc-be-media/forward`, // 共享层文件上传使用 dataType: 'media'
  // 当设置成false时,不会Message.error();
  // 当设置为true 时,会自动Message.error(data.res_msg),
  // 在请求的catch((error)=>{error.hideError()})不会执行Message.error(data.res_msg)
  isShowError: true,
  settleRequest: function settleRequest(config) { // 请求拦截处理
    const {
      luRootUrl, luRootUrlMedia, dataType, baseURL,
    } = config || {};
    let rootUrl = luRootUrl;
    if (config.data && utils.isFormData(config.data) && dataType === 'media') {
      rootUrl = luRootUrlMedia;
    }
    if (config.data && !utils.isFormData(config.data)) { // FormData
      config.data = `param=${JSON.stringify(serialize(config.data))}`;
    }
    config.baseURL = `${rootUrl}${baseURL}`; // axios fullUrl =  baseURL(axios) + url = rootUrl + baseURL + url; 当url 为绝对路径(://) fullUlr = url;
    return config;
  },
  validateStatus: function validateStatus(status) {
    return status >= 200 && status < 400;
  },
  validateCode: function validateCode(code) {
    return code === '0' || code === '0000';
  },
  settle401: (error) => { // status: 401 调用
    if (window.location.href.indexOf('/wmc-be-admin/wmc-web/login') === -1) {
      window.location.href = `/wmc-be-admin/wmc-web/login?fromUrl=${location.href}`;
    }
  },
  settleError: () => { // 不是 validateCode 时 调用

  },
};

具体应用

引用方式跟 axios 一样 参考:https://github.com/axios/axios http://www.axios-js.com/docs/

axios(config)
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])

使用案例:

一、axios.all(iterable) axios.all = function all(promises) { return Promise.all(promises); };

用例 // hooks all (class 组件一样)

  import request, {useRequest} from '@luna/be-request';

  const [tablelist, requestTablelist]  = useRequest({method: 'post', url: '/post', data: {name:'shangyy', age:18 }});
  const [panellist, requestPanellist]  = useRequest({method: 'post', url: '/post'});

  function handleSubmit() {
    request.all([
      requestTablelist(),
      requestPanellist(),
    ]).then(request.spread(function (list1, list2) {
      console.log(list1);
      console.log(list2);
    }));
  }

二、进度 progress

import request from '@luna/be-request';

request({
  method: 'post',
  url: 'xxx',
  data:{},
  onDownloadProgress: (data)=>{
     console.log('panellist onDownloadProgress',data);
  },
})

三、取消请求 // Expose Cancel & CancelToken axios.Cancel = require('./cancel/Cancel'); axios.CancelToken = require('./cancel/CancelToken'); axios.isCancel = require('./cancel/isCancel');

import React from 'react';
import { Search } from '@alifd/next';
import IceContainer from '@icedesign/container';
import request from '@luna/be-request';

class CancelRequest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      resData: null,
    };
    this.cancelToken = null;
  }

  onSearch = async (val) => {
    if(this.cancelToken){
      this.cancelToken.cancel();
    }
    this.cancelToken = request.CancelToken.source();
    try {
      const resData = await request.post('/post',{val},{cancelToken: this.cancelToken.token});
      this.setState({ resData });
    } catch (err) {
      // err.hideError();
      if(request.isCancel(err)){
        console.log('Request canceled', err.message); 
      }
      this.setState({ resData: null });
    }
  }

  ......

}

export default CancelRequest;

贡献 加入我们

npm run dev
源码在src 中 ,监听代码改动,打包更新到dist

npm run build
打包代码 dist; package.json main: "dist/index"

npm run test
集成jest单元测试, 修改代码写入对应的单元测试

实际项目测试
执行以下命令就可以通过link 的方式在 example 项目中测试,数据可以mock
npm link
cd example
npm install 安装example依赖
npm link @luna/be-request
npm start

提交代码
提交代码会进行 eslint , commit lint 检测, 不通过则不能提交代码成功
git add filename
npm run cz
git push origin 分支