介绍
基于Promise
的Http
库。
使用
技巧
封装一个http请求
import axios from "axios";
import { Toast } from "vant";
class request {
constructor() {
this.config = {
baseURL: 'https://forguo.cn',
timeout: 10000,
};
}
request(options) {
const config = Object.assign({}, this.config, options);
const instance = axios.create();
this.setInterceptors(instance);
return instance(config); // 返回axios实例的执行结果
}
setInterceptors(instance) {
instance.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
config.headers.common['Authorization'] = 'Bearer ' + token;
return config;
}, err => {
return Promise.reject(err);
});
instance.interceptors.response.use((res) => {
console.log(JSON.stringify(res));
if (res.status === 200 && res.data.code === 200) {
return Promise.resolve(res.data);
} else {
Toast(res.data.message || res.statusText);
if (res.data.code === 401) {
console.log('token失效,重新授权!')
localStorage.clear();
window.login();
}
return Promise.reject(res.data);
}
}, (err) => {
console.log(JSON.stringify(err));
Toast(err.data.message || err.statusText);
return Promise.reject(err);
})
}
}
export default new request();
基本原理
适配器
/**
* @Author: forguo
* @Path: libs/defaults.js
* @Date: 2021/9/21 18:14
* @Description: 获取默认适配器
*/
function getDefaultAdapter() {
var adapter;
// 判断是否支持 XMLHttpRequest,支持则为浏览器端
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = require('./adapters/xhr');
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = require('./adapters/http');
}
return adapter;
}
浏览器
/**
* @Author: forguo
* @Path: libs/adapters/xhr
* @Date: 2021/9/21 18:07
* @Description: 一个简单的xhr发送步骤
*/
// request实例
const request = XMLHttpRequest
// 打开链接
request.open(url);
// 监听状态变化
request.onreadystatechange = function handleLoad() {
// ...
}
// 发送请求
request.send(requestData);
Node
/**
* @Author: forguo
* @Path: libs/adapters/http
* @Date: 2021/9/21 18:25
* @Description: node端http请求
*/
var http = require('http');
var https = require('https');
var httpFollow = require('follow-redirects').http;
var httpsFollow = require('follow-redirects').https;
var url = require('url');
// https判断
var isHttps = /https:?/;
var parsed = url.parse(fullPath);
var protocol = parsed.protocol || 'http:';
// 请求
var transport;
var isHttpsRequest = isHttps.test(protocol);
var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
if (config.transport) {
transport = config.transport;
} else if (config.maxRedirects === 0) {
transport = isHttpsProxy ? https : http;
} else {
if (config.maxRedirects) {
options.maxRedirects = config.maxRedirects;
}
transport = isHttpsProxy ? httpsFollow : httpFollow;
}
// Create the request
var req = transport.request(options, function handleResponse(res) {
// ...
})
发送请求
/**
* @Author: forguo
* @Path: libs/dispatchRequest
* @Date: 2021/9/21 18:16
* @Description: 发送请求
*/
// 获取适配器
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(data => {
// ...
return data;
}, (err) => {
// ...
return new Promise.reject(err);
});
axios.all
// axios.all的实现使用了Promise.all
axios.all = function all(promises) {
return Promise.all(promises);
};