axios库 http://www.axios-js.com/
axios的使用方式
第一种混入模式:
document.querySelector(".btn1").onclick = function(){
axios.get("/axios").then(res=>{
console.log(res.data);
})
}
第二种工厂模式函数:(函数写法,配置参数更丰富)
get
document.querySelector(".btn1").onclick = function(){
axios({
method:"get",
url:"/axios"
}).then(res=>{
console.log(res.data);
})
}
post(带data)
document.querySelector(".btn2").onclick = function(){
const params = new URLSearchParams();
params.append('name', '张三');
params.append('age', 20);
axios({
method:"post",
url:"/axiosPost",
// data:params,
data:JSON.stringify({name:"张三",age:21}),
headers:{
"content-type":"application/json"
}
}).then(res=>{
console.log(res.data);
})
}
路由设置:
拦截器
可以拦截所有请求 或者返还,鉴权---->头部加上鉴权信息带给后端做验证
拦截管理器
class InterceptorManager {
constructor() {
this.handlers = [];
}
use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
}
把axios放到类里面管理,同时通过函数执行
简单封装axios,加入拦截管理器网络队列
// 混入; 把函数及当成函数有当成对象使用;---》 axios()/axios.get()/axios.post。。。。;
// 拦截器;队列数组(函数没有执行;);--》控制执行顺序 [网络请求] --》网络请求前unshift request 拦截器(多个InterceptorManager); ---》网络请求后 push response 拦截器 ---》 异步执行;
// 适配器; ---》 判断环境执行不同代码;
let utils = {
extends(a,b,context){
for(let key in b){
if(b.hasOwnProperty(key)){
if(typeof b[key]==='function'){
// 函数;
a[key] = b[key].bind(context);
}else{
// 属性;
a[key] = b[key]
}
}
}
}
}
class Axios{
constructor(){
this.test = "一些属性";
this.interceptors = {
request:new InterceptorManager(),
response:new InterceptorManager()
}
this.adapter = new Adapter();
}
request(config){
// 组装队列;
let chain = [this.dispatchXhr.bind(this),undefined];
this.interceptors.request.handles.forEach(interceptor=>{
chain.unshift(interceptor.fulfilled,interceptor.rejected);
})
this.interceptors.response.handles.forEach(interceptor=>{
chain.push(interceptor.fulfilled,interceptor.rejected);
})
let primose = Promise.resolve(config);
while(chain.length>0){
primose = primose.then(chain.shift(),chain.shift());
}
// [function fn1(){},function fn2(){}....];
// chain.shift()====function fn1(){}
// primose.then(function fn1(){},function fn2(){});
return primose;
// console.log(chain);
// [ful1,rej1,ful2,rej2,this.xhr,undefined,ful1,rej1,ful2,rej2]
// this.xhr(config);
}
dispatchXhr(config){
// 判断环境?特殊的变量;
if(typeof process !=='undefined'){
// 服务端
return this.adapter.http(config);
}else{
// 客户端
return this.adapter.xhr(config);
}
}
}
// 适配器:adapter 适配node端和js端;
class Adapter{
http(config){
// 在nodejs端发送请求的;(服务端代理)
return new Promise((resolve, reject) => {
const http = require("http");
// const https = require("https")
// http://localhost:4000/axios
const urls = require("url");
let { data = null, url, method = 'get', params, headers = {} } = config;
let pathObj = urls.parse(url)
let options = {
host: pathObj.hostname,
port: pathObj.port,
path: pathObj.path,
method: config.method.toUpperCase(),
headers: headers
};
// let options = {
// host:'localhost',
// port:3000,
// path:'/atest',
// method:'POST',
// headers:{
// "content-type":"application/json"
// }
// }
// console.log(options);
let request = http.request(options, res => {
let reslut = "";
res.on("data", chunk => {
reslut += chunk;
})
res.on("end", () => {
console.log(reslut.toString())
resolve(JSON.parse(reslut.toString()));
})
})
request.on("error", err => {
reject(err);
})
request.end();
})
console.log("node端执行了",config);
}
xhr(config){
// 客户端请求;
return new Promise(resolve=>{
// console.log(config)
// let xhr = new XMLHttpRequest();
// console.log("发送请求",config);
let xhr = new XMLHttpRequest();
let {url="",data=null,method='get',headers={}} = config;
xhr.open(method,url,true);
xhr.onload = function(){
// 对返还做包装;
resolve(xhr.responseText);
}
xhr.send(data);
})
}
}
class InterceptorManager{
constructor(){
this.handles = [];
}
use(fulfilled,rejected){
this.handles.push({
fulfilled,
rejected
});
}
}
// Axios.prototype['get'] = function(){
// config.method = "get";
// this.request(config);
// }
let methodsArr = ['get',"post","put","delete","options","head"];
methodsArr.forEach(method=>{
Axios.prototype[method] = function(config){
config.method = method;
return this.request(config);
}
})
// console.dir(Axios);
function createInstance(){
let context = new Axios();
let instance = context.request.bind(context);
// 把原型里的方法混入到instance里;
utils.extends(instance,Axios.prototype,context);
utils.extends(instance,context);
console.dir(instance);
return instance
}
let axios = createInstance();
if(typeof process !=='undefined'){
// 服务端
module.exports = axios;
}
// axios
// function test(){
// }
// test();
// test['get'] = function(){};....
请求axios