介绍

基于PromiseHttp库。

使用

技巧

封装一个http请求

  1. import axios from "axios";
  2. import { Toast } from "vant";
  3. class request {
  4. constructor() {
  5. this.config = {
  6. baseURL: 'https://forguo.cn',
  7. timeout: 10000,
  8. };
  9. }
  10. request(options) {
  11. const config = Object.assign({}, this.config, options);
  12. const instance = axios.create();
  13. this.setInterceptors(instance);
  14. return instance(config); // 返回axios实例的执行结果
  15. }
  16. setInterceptors(instance) {
  17. instance.interceptors.request.use((config) => {
  18. const token = localStorage.getItem('token');
  19. config.headers.common['Authorization'] = 'Bearer ' + token;
  20. return config;
  21. }, err => {
  22. return Promise.reject(err);
  23. });
  24. instance.interceptors.response.use((res) => {
  25. console.log(JSON.stringify(res));
  26. if (res.status === 200 && res.data.code === 200) {
  27. return Promise.resolve(res.data);
  28. } else {
  29. Toast(res.data.message || res.statusText);
  30. if (res.data.code === 401) {
  31. console.log('token失效,重新授权!')
  32. localStorage.clear();
  33. window.login();
  34. }
  35. return Promise.reject(res.data);
  36. }
  37. }, (err) => {
  38. console.log(JSON.stringify(err));
  39. Toast(err.data.message || err.statusText);
  40. return Promise.reject(err);
  41. })
  42. }
  43. }
  44. export default new request();

基本原理

适配器

  1. /**
  2. * @Author: forguo
  3. * @Path: libs/defaults.js
  4. * @Date: 2021/9/21 18:14
  5. * @Description: 获取默认适配器
  6. */
  7. function getDefaultAdapter() {
  8. var adapter;
  9. // 判断是否支持 XMLHttpRequest,支持则为浏览器端
  10. if (typeof XMLHttpRequest !== 'undefined') {
  11. // For browsers use XHR adapter
  12. adapter = require('./adapters/xhr');
  13. } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
  14. // For node use HTTP adapter
  15. adapter = require('./adapters/http');
  16. }
  17. return adapter;
  18. }

浏览器

  1. /**
  2. * @Author: forguo
  3. * @Path: libs/adapters/xhr
  4. * @Date: 2021/9/21 18:07
  5. * @Description: 一个简单的xhr发送步骤
  6. */
  7. // request实例
  8. const request = XMLHttpRequest
  9. // 打开链接
  10. request.open(url);
  11. // 监听状态变化
  12. request.onreadystatechange = function handleLoad() {
  13. // ...
  14. }
  15. // 发送请求
  16. request.send(requestData);

Node

  1. /**
  2. * @Author: forguo
  3. * @Path: libs/adapters/http
  4. * @Date: 2021/9/21 18:25
  5. * @Description: node端http请求
  6. */
  7. var http = require('http');
  8. var https = require('https');
  9. var httpFollow = require('follow-redirects').http;
  10. var httpsFollow = require('follow-redirects').https;
  11. var url = require('url');
  12. // https判断
  13. var isHttps = /https:?/;
  14. var parsed = url.parse(fullPath);
  15. var protocol = parsed.protocol || 'http:';
  16. // 请求
  17. var transport;
  18. var isHttpsRequest = isHttps.test(protocol);
  19. var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
  20. if (config.transport) {
  21. transport = config.transport;
  22. } else if (config.maxRedirects === 0) {
  23. transport = isHttpsProxy ? https : http;
  24. } else {
  25. if (config.maxRedirects) {
  26. options.maxRedirects = config.maxRedirects;
  27. }
  28. transport = isHttpsProxy ? httpsFollow : httpFollow;
  29. }
  30. // Create the request
  31. var req = transport.request(options, function handleResponse(res) {
  32. // ...
  33. })

发送请求

  1. /**
  2. * @Author: forguo
  3. * @Path: libs/dispatchRequest
  4. * @Date: 2021/9/21 18:16
  5. * @Description: 发送请求
  6. */
  7. // 获取适配器
  8. var adapter = config.adapter || defaults.adapter;
  9. return adapter(config).then(data => {
  10. // ...
  11. return data;
  12. }, (err) => {
  13. // ...
  14. return new Promise.reject(err);
  15. });

axios.all

  1. // axios.all的实现使用了Promise.all
  2. axios.all = function all(promises) {
  3. return Promise.all(promises);
  4. };