搭建HTTP 服务
json-server网址:json-server - npm
axios 对象创建模拟实现
axios既可以当做函数直接调用,也可以当做对象调用内部函数 – 先生成函数,再往函数原型上加方法
// 构造函数
function Axios(config){
// 初始化
this.defaults = config, //为了创建defaults的默认属性
// 拦截器
this.intercepters = {
request: {
},
response: {
}
}
}
/**
* 原型添加相关的方法
* axios 请求最终都是通过调用request方法去请求XMLHttpRequest
*/
Axios.prototype.request = function(config) {
console.log('发送 AJAX 请求,请求类型:' + config.method)
}
Axios.prototype.get = function(config) {
return this.request({
method: 'GET'})
}
Axios.prototype.post = function(config) {
return this.request({
method: 'POST'})
}
// 声明函数
function createInstance(config) {
/**
* 实例化一个对象
* 可以context.get() context.post(), 但是不能当做函数使用 context()
*/
let context = new Axios(config);
/**
* 创建请求函数
* instance 可以当做一个函数调用 instance(),
* 此时instance.get(), instance.post() 不能用
*/
let instance = Axios.prototype.request.bind(context);
// 将 Axios.prototype 对象中的方法添加到 instance 函数对象中
Object.keys(Axios.prototype).forEach(key => {
instance[key] = Axios.prototype[key].bind(context); // 让方法始终指向 context 实例
})
Object.keys(context).forEach(key => {
instance[key] = context[key]
})
return instance
}
let axios = createInstance()
axios({
method: 'get'})
axios.get()
axios.post()
模拟axios实现发送请求
axios 是基于 promise 的http客户端,可在浏览器与node.js 服务器上发送请求
axios 是对 XMLHttpRequest的封装
axios 请求过程: axios 调用 request ,request 再调用 dispatch(适配器),dispatch 再调用 xhr。再逐步往回返回结果xhr -> dispatch -> request -> axios
// axios 发送请求, axios Axios.prototype.request bind
//1. 构造函数
function Axios(config){
this.config = config
}
Axios.prototype.request = function(config) {