@51yzone/request-extend 中文文档教程

发布于 4年前 浏览 24 项目主页 更新于 3年前

统一请求库


基于 axios 封装了各个端请求库:PC,Taro,支付宝原生小程序,钉钉原生小程序,h5

何时使用

  • 请求后端 api

浏览器支持

IE 11+,各自小程序,Taro 跨端框架

API

RequestExtend

requestGet

简化 get 请求

requestPost

简化 post 请求,内置 token 请求

requestForm

简化 get 请求,内置 form 生成

request

同 axios.request 官方请求 api

getUploadHeader

上传需要单独获取请求头

安装

npm install @51yzone/request-extend --save

运行

# 默认开启服务器,地址为 :http://local:8000/

# 能在ie9+下浏览本站,修改代码后自动重新构建,且能在ie10+运行热更新,页面会自动刷新
npm run start

# 构建生产环境静态文件,用于发布文档
npm run site

代码演示

钉钉 h5

使用 AdapterDingDingH5 实现 钉钉 h5 的快速接入

import { Button, Modal, message, notification } from 'antd';
import RequestExtend, {
  getParamValue,
  ClientSdkDingDingH5Old,
  AdapterDingDingH5,
} from '@51yzone/request-extend';
import { Dialog } from 'saltui';
import jquery from 'jquery';
import * as dingtalk from 'dingtalk-jsapi';
window.$ = jquery;
const clientSdk = new ClientSdkDingDingH5Old({
  window,
  Dialog,
  dd: dingtalk,
});

const adapterH5 = new AdapterDingDingH5(clientSdk);
const initData = {
  corpid: 'ding6aad29a10ac2c67735c2f4657eb6378f',
  type: '99',
};
const isLocal = window.location.protocol === 'http:';
const baseUrl = !isLocal ? '' : 'https://dtest-property002.51yzone.com';
// C端
const request = new RequestExtend(
  {
    withCredentials: true,
    // 编译到线上会变成相对路径
    baseURL: baseUrl,
  },
  adapterH5,
);

// 设置初始化数据
const setInitData = function (initDataNew) {
  // console.log("setInitData:", initDataNew);
  adapterH5.setInitData({ params: { ...initData, ...initDataNew } });
};
// 设置初始化数据
const initJSSDK = function (initDataNew) {
  return adapterH5.initJSSDK(baseUrl, {
    ...initData,
    ...initDataNew,
  });
};
const corpid = getParamValue('corpid');
const type = getParamValue('type');
const initDataNow = corpid ? { corpid, type } : {};

setInitData(initDataNow);
initJSSDK(initDataNow);
class App extends React.Component {
  render() {
    return [
      <Button
        key="get"
        onClick={() =>
          request
            .requestGet('/shared/common/rest/jsontoken', { a: 1 }, { noAuth: true })
            .then(resData =>
              Modal.info({
                content: JSON.stringify(resData),
              }),
            )
        }
      >
        Get
      </Button>,
      <Button
        key="post"
        onClick={() =>
          request
            .requestForm(
              '/homeindex/login/ajax/submit',
              { userName: '13400609213', password: '' },
              { noMessage: true },
            )
            .then(() => {
              Modal.info({
                title: '登陆成功',
              });
            })
            .catch(error => message.error(error.messageContent))
        }
      >
        Post
      </Button>,
      <Button
        key="getUploadHeader"
        onClick={() => request.getUploadHeader().then(header => alert(JSON.stringify(header)))}
      >
        getUploadHeader
      </Button>,
      <Button
        key="getSessionDataBody"
        onClick={() => alert(JSON.stringify(request.getSessionDataBody()))}
      >
        getSessionDataBody
      </Button>,
      <Button
        key="getSessionDataId"
        onClick={() => alert(JSON.stringify(request.getSessionDataId()))}
      >
        getSessionDataId
      </Button>,
    ];
  }
}
ReactDOM.render(<App />, mountNode);

PC 管理中台

使用 AdapterPC 实现 PC 管理中台的快速接入

import { Button, Modal, message, notification } from 'antd';
import RequestExtend, { AdapterPC, ClientSdkPC, clientSetting } from '@51yzone/request-extend';
const clientSdkPC = new ClientSdkPC({ Modal, message, notification, window });
clientSdkPC.handleRedirectUrl = redirectUrl => {
  alert(redirectUrl);
};
const adapterPC = new AdapterPC(clientSdkPC, { ...clientSetting.pc });
const request = new RequestExtend(
  {
    withCredentials: true,
    baseURL: 'https://dtest-property001.51yzone.com',
  },
  adapterPC,
);

class App extends React.Component {
  render() {
    return [
      <Button
        key="get"
        onClick={() =>
          request
            .requestGet('/shared/common/rest/jsontoken', { a: 1 }, { noAuth: true })
            .then(resData =>
              Modal.info({
                content: JSON.stringify(resData),
              }),
            )
        }
      >
        Get
      </Button>,
      <Button
        key="post"
        onClick={() =>
          request
            .requestForm(
              '/homeindex/login/ajax/submit',
              { userName: '13400609213', password: '' },
              { noMessage: true },
            )
            .then(() => {
              Modal.info({
                title: '登陆成功',
              });
            })
            .catch(error => message.error(error.messageContent))
        }
      >
        Post
      </Button>,
      <Button
        key="redrect"
        onClick={() =>
          request.requestGet(
            '/customapp/web/welfare/org/rest/selectWelfareList?pageSize=20&pageNum=1',
          )
        }
      >
        redrect
      </Button>,
      <Button
        key="getUploadHeader"
        onClick={() => request.getUploadHeader().then(header => alert(JSON.stringify(header)))}
      >
        getUploadHeader
      </Button>,
      <Button
        key="getSessionDataBody"
        onClick={() => alert(JSON.stringify(request.getSessionDataBody()))}
      >
        getSessionDataBody
      </Button>,
      <Button
        key="getSessionDataId"
        onClick={() => alert(JSON.stringify(request.getSessionDataId()))}
      >
        getSessionDataId
      </Button>,
    ];
  }
}
ReactDOM.render(<App />, mountNode);

PC 管理中台新版

使用 AdapterPCNew 实现 PC 管理中台新版的快速接入

import { Button, Modal, message, notification } from 'antd';
import RequestExtend, { AdapterPCNew, ClientSdkPC } from '@51yzone/request-extend';
const clientSdkPC = new ClientSdkPC({ Modal, message, notification, window });
clientSdkPC.handleRedirectUrl = redirectUrl => {
  alert(redirectUrl);
};
const adapterPC = new AdapterPCNew(clientSdkPC, {});
const request = new RequestExtend(
  {
    withCredentials: true,
    baseURL: 'https://community-console-test.51yzone.com',
  },
  adapterPC,
);
class App extends React.Component {
  render() {
    return [
      <Button
        key="get"
        onClick={() =>
          request.requestGet('/seed', { a: 1 }, { noAuth: true }).then(resData =>
            Modal.info({
              content: JSON.stringify(resData),
            }),
          )
        }
      >
        Get
      </Button>,
      <Button
        key="post"
        onClick={() =>
          request
            .requestForm(
              '/pageframework/login/ajax/submit',
              { userName: '13688888888', password: '123456' },
              { noAuth: true },
            )
            .then(() => {
              Modal.info({
                title: '登陆成功',
              });
            })
            .catch(error => message.error(error.messageContent))
        }
      >
        Post
      </Button>,
      <Button
        key="redrect"
        onClick={() => request.requestGet('/pageframework/login/ajax/userinfo')}
      >
        redrect
      </Button>,
      <Button
        key="getUploadHeader"
        onClick={() => request.getUploadHeader().then(header => alert(JSON.stringify(header)))}
      >
        getUploadHeader
      </Button>,
    ];
  }
}
ReactDOM.render(<App />, mountNode);

Taro

使用 AdapterTaro 实现 Taro 开发的小程序快速接入新后台规范

import RequestExtend, { AdapterTaro, ClientSdkBase, clientSetting } from '@51yzone/request-extend';
import { Button, Modal } from 'antd';
import Taro from '@rtarojs/taro';
const { getStorageSync, setStorageSync, showModal, showToast } = Taro;
const clientSDK = new ClientSdkBase({
  getStorageSync,
  setStorageSync,
  showModal,
  showToast,
  getAuthCode: () =>
    Promise.resolve({
      authCode: '11',
    }),
});
clientSDK.handleRedirectUrl = redirectUrl => {
  alert(redirectUrl);
};
const adapter = new AdapterTaro(clientSDK, {
  headerDefault: { appId: '11' },
  ...clientSetting.alipayNew,
});
const request = new RequestExtend(
  {
    baseURL: 'https://community-test.51yzone.com',
  },
  adapter,
);
class App extends React.Component {
  render() {
    return [
      <Button
        key="get"
        onClick={() =>
          request.requestGet('/seed', { a: 1 }, { noAuth: true }).then(resData =>
            Modal.info({
              content: JSON.stringify(resData),
            }),
          )
        }
      >
        Get
      </Button>,
      <Button key="post" onClick={() => request.requestPost('/pageframework/login/ajax/submit')}>
        Post
      </Button>,
      <Button
        key="redrect"
        onClick={() => request.requestGet('/pageframework/login/ajax/userinfo')}
      >
        redrect
      </Button>,
      <Button
        key="getUploadHeader"
        onClick={() => request.getUploadHeader().then(header => alert(JSON.stringify(header)))}
      >
        getUploadHeader
      </Button>,
    ];
  }
}
ReactDOM.render(<App />, mountNode);

h5

使用 AdapterH5 实现移动端 h5 的快速接入

import { Button, Modal, message } from 'antd';
import RequestExtend, { AdapterH5, ClientSdkBase, clientSetting } from '@51yzone/request-extend';
const { getStorageSync, setStorageSync, showModal, showToast } = {
  getStorageSync: () => {},
  setStorageSync: () => {},
  showModal: ({ content }) => {
    alert('error:' + content);
  },
  showToast: ({ title }) => {
    alert('error:' + title);
  },
};
const clientSdk = new ClientSdkBase({ getStorageSync, setStorageSync, showModal, showToast });
const adapterH5 = new AdapterH5(clientSdk, { ...clientSetting.alipay });
const request = new RequestExtend(
  {
    baseURL: 'https://dtest-property.51yzone.com',
  },
  adapterH5,
);
class App extends React.Component {
  render() {
    return [
      <Button
        key="get"
        onClick={() =>
          request
            .requestGet('/shared/common/rest/jsontoken', { a: 1 }, { noAuth: true })
            .then(resData =>
              Modal.info({
                content: JSON.stringify(resData),
              }),
            )
        }
      >
        Get
      </Button>,
      <Button
        key="get2"
        onClick={() =>
          request
            .requestGet('https://dtest-prod.51yzone.com/yzh5/m/miniapp/repair/rest/savewkst', {
              a: 1,
            })
            .then(resData =>
              Modal.info({
                content: JSON.stringify(resData),
              }),
            )
        }
      >
        Get2
      </Button>,
      <Button
        key="getUploadHeader"
        onClick={() => request.getUploadHeader().then(header => alert(JSON.stringify(header)))}
      >
        getUploadHeader
      </Button>,
    ];
  }
}
ReactDOM.render(<App />, mountNode);
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文