gh-qqnews-request

前端数据请求模块

Usage no npm install needed!

<script type="module">
  import ghQqnewsRequest from 'https://cdn.skypack.dev/gh-qqnews-request';
</script>

README

腾讯新闻的数据请求模块

背景介绍(Background)

version size

gh-qqnews-request: 是基于axios实现的前端数据请求模块,在 axios 的基础上,额外封装了 jsonp 和新闻客户端 jsapi 的两种数据请求方式。

axios 是一个非常优秀的前端数据请求模块,提供了请求数据和响应数据的拦截器,并可以在浏览器和 node 中使用。

安装(Install)

使用 tnpm:

$ tnpm install gh-qqnews-request

使用 npm:

$ npm install gh-qqnews-request

使用 bower:

$ bower install gh-qqnews-request

使用 yarn:

$ yarn add gh-qqnews-request

使用 jsDelivr 的 CDN 地址:

<script src="https://cdn.jsdelivr.net/npm/gh-qqnews-request"></script>

使用 unpkg 的 CDN 地址:

<script src="https://unpkg.com/gh-qqnews-request"></script>

使用方式

引入进来之后,就可以使用request进行数据请求了。这里提供了两种方式:

  • 简易方式;
  • 完全基于 axios 的使用方式;

简易方式

建议方式中返回的数据就是接口返回的数据。以 es6 的 import 为例:

import request from 'gh-qqnews-request';

使用方式

// 只有一个url,默认为get方式请求
request('https://api.prize.qq.com/v1/newsapp/answer/share/oneQ?qID=506336')
  .then((result) => console.log(result))
  .catch((err) => console.error(err));
// 带有参数,默认为get方式请求
request('https://api.prize.qq.com/v1/newsapp/answer/share/oneQ', {
  qID: 506336,
})
  .then((result) => console.log(result))
  .catch((err) => console.error(err));
// 带有参数,并进行配置
request(
  'https://api.prize.qq.com/v1/newsapp/answer/share/oneQ',
  {
    qID: 506336,
  },
  {
    method: 'post',
    timeout: 6000,
  }
)
  .then((result) => console.log(result))
  .catch((err) => console.error(err));
// 没有参数,并需要配置时,需要将参数位置设置为null
request('https://api.prize.qq.com/v1/newsapp/answer/share/oneQ?qID=506336', null, {
  method: 'get',
  timeout: 6000,
})
  .then((result) => console.log(result))
  .catch((err) => console.error(err));

jsonp 的方式需要特别标注,其他的均会根据环境自行判断。

jsonp 的优先级最高,当配置了 jsonp 方式的请求,则不会根据环境自行选择对应的请求方式,无论哪个环境,都是使用的 jsonp。

// 带有参数,并进行配置
request(
  'https://api.prize.qq.com/v1/newsapp/answer/share/oneQ',
  {
    qID: 506336,
  },
  {
    dataType: 'jsonp', // 表明是jsonp请求
    jsonpCallback: 'callback', // 回调的方法名,默认是callback
  }
)
  .then((result) => console.log(result))
  .catch((err) => console.error(err));

参数 config 的配置

request 的数据格式如下:

request(
    url: string, // 第一个参数请求的url
    data?: object, // 请求中需要的数据,不论get和post,均放在这里,均是object类型
    config?: HungerRequestConfig // 与axios中的配置要求一样,并额外扩展了两个参数dataType和jsonpCallback
)

config 中的字段,只在当前请求中有效,以下参数均为可选参数,在有必要时填写即可:

字段 类型 说明
baseURL 拼接在 url 前面的;
若 url 为绝对链接,则不进行拼接
method 请求方式, get 和 post 默认为 post
timeout number 请求超时的时间,默认为 16000ms
dataType 是否为 jsonp 设置为 jsonp,按照 jsonp 进行请求
jsonpCallback 回调参数的设置 默认为 callback
data object 所有请求中都会携带的参数

defaults 的配置

request 还有个 defaults 的属性可以设置,这个配置是所有的请求都有效的。字段与 config 保持一致。

request.defaults.baseURL = 'https://api.prize.qq.com'; // 设置拼接在url前面的参数,若url为绝对链接,则不进行拼接
request.defaults.method = 'post'; // 数据请求方式
request.defaults.timeout = 5000; // 超时时间

request('/v1/newsapp/answer/share/oneQ?qID=506336');
// https://api.prize.qq.com/v1/newsapp/answer/share/oneQ?qID=506336

若请求的接口根据不同的环境需要不同的域名,可以直接在defaults.baseURL中设置接口的域名,然后 request 直接使用接口的路径,而不用再关心域名是什么。例如:

export const TEST_API_ORIGIN = `https://test.api.qq.com`;
export const PRE_API_ORIGIN = `https://pre.api.qq.com`;
export const PRO_API_ORIGIN = `https://production.api.qq.com`;

request.defaults.baseURL = (() => {
  switch (ENV) {
    case 'local':
    case 'testing': {
      return TEST_API_ORIGIN;
    }
    case 'pre': {
      return PRE_API_ORIGIN;
    }
    default: {
      return PRO_API_ORIGIN;
    }
  }
})();

request('/v1/newsapp/answer/share/oneQ?qID=506336');

拦截器

在 request 模块中添加了拦截器,可以很方便地处理请求和响应。使用方式与 axios 中的拦截器一模一样。

// 获取当前的时间
const getTime = () => {
  if (typeof window.performance === 'object' && typeof performance.now === 'function') {
    return window.performance.now();
  }
  return new Date().getTime();
};

// 请求拦截器
request.interceptors.request.use((config: any) => {
  console.log('request', config.url);

  // 添加请求的时间
  return { ...config, ...{ requesttime: getTime() } };
});
request.interceptors.response.use(
  (response: any) => {
    // 输出当前请求使用的时间
    console.log('response', response.config.url, getTime() - response.config.requesttime);
    return response;
  },
  (error: any) => {
    console.log(error.response, error.config);
    return Promise.reject(error);
  }
);

复杂方式

复杂方式的介绍方式就简单多了,使用方式与 axios 的方式完全一样,并带有 axios 所有的功能,例如拦截器等。

  • axios 的 github:https://github.com/axios/axios
  • 中文文档:http://axios-js.com/zh-cn/docs/index.html

使用复杂方式时,需要从 request 中取出 haxios,haxios 中也包含有 jsonp 和新闻客户端的 jsapi 请求

const { haxios } = request;

haxios('https://api.prize.qq.com/v1/newsapp/answer/share/oneQ', {
  params: {
    qID: 506336,
  },
})
  .then(console.log)
  .catch(console.error);

而且 haxios 中接口返回的数据与 axios 官方的保持一致:

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the HTTP headers that the server responded with
  // All header names are lower cased and can be accessed using the bracket notation.
  // Example: `response.headers['content-type']`
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

协议(License)

MIT

ChangeLog

ChangeLog