美文网首页饥人谷技术博客
Axios的实现和MVC类构造函数使用

Axios的实现和MVC类构造函数使用

作者: 飞天小猪_pig | 来源:发表于2021-10-10 15:58 被阅读0次

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
------------从浏览器中创建 XMLHttpRequest
------------从 node.js 发出 http 请求
------------支持 Promise API
------------拦截请求和响应
------------转换请求和响应数据
------------取消请求
------------自动转换JSON数据
------------客户端支持防止 CSRF/XSRF

点击代码:axios的实现--包括拦截器使用

//interceptors拦截器
//在真正返回response时使用
axios.interceptors.response.use(function(response){
    let config=response.config  //config查看响应有啥配置
    let {method,url,data}=config  //data是请求的data
    if(url==='/books/1' && method==='get'){
      response.data={   //data是响应的data
         name:'JS高级程序设计',
         number:2,
         id:1
     }
    }
     return response
 })

1、axios 的拦截器是在 jsbin.com中进行的。
2、如果你在本地实验会发现拦截器不起作用,这是正常的。
3、你如果想让本地的拦截器也起作用,就需要自己写 server.js 来响应所有请求。

MVC类构造函数使用(代码优化)

MVC原代码:

let model={
  data:{ name:'', number:0, id:' },
  fetch(id){
    return axios.get(`/books/${id}`).then((response)=>{ ... })
  },
  update(data){
    let id = this.data.id
    return  axios.put(`/books/${id}`,data).then((response)=>{ ... })
  }
}

MVC类--构造函数实现后的代码:

//创建构造函数
function Model(options) {
    this.data = options.data
    this.resource=options.resource
  }
  //让公有属性挂在原型链上
Model.prototype.fetch = function(id) {
  return axios.get(`/${this.resource}s/${id}`).then((response) => { ... })
}
Model.prototype.update = function(data) {
  let id = this.data.id
  return axios.put(`/${this.resource}s/${id}`, data).then((response) => {...})
}

//----------上面是MVC类,下面是对象
let model = new Model({
  data: {name: '',number: 0,id: ''},
  resource:'book'
})

构建构造函数的方法:
1、声明一个函数如:Model,让私有数据传入函数中
function Model(){}
2、让每次重复做的事情挂在原型链上变成公有属性
Model.prototype.fetch = function(id) {}
3、调用对象new Model()
let model = new Model({})

点击:MVC类构造函数实现全部代码

相关文章

网友评论

    本文标题:Axios的实现和MVC类构造函数使用

    本文链接:https://www.haomeiwen.com/subject/wkvqoltx.html