关于前端:axios基础封装

9次阅读

共计 1345 个字符,预计需要花费 4 分钟才能阅读完成。

request.js

新建文件夹 network 在文件新建 request.js

import axios from 'axios'
export function request (config) {
  // 1 创立 axios 实例
  const intstance = axios.create({
    baseURL: 'https://localhost:44314',
    timeout: 5000
    // contentType: 'application/json;charset=UTF-8',
    // dataType: 'json'
  })
  // 1.axios 拦截器
  intstance.interceptors.request.use(config => {return config}, er => {})
  // 1.axios 响应拦挡拦挡
  intstance.interceptors.response.use(res => {return res}, er => {})
  return intstance(config)
}
export default request // 导出 

main. 挂载配置

import request from '@/network/request'

new Vue({
  el: '#app',
  router,
  store,
  request, // 封装的 axios
  components: {App},
  template: '<App/>'

})

vue 组件调用

在须要应用 axios 的 vue 组件调用

import request from '@/network/request'

  request({ // 查问所有
        url: '/api/Gj'
      }).then(res => {this.tableData = res.data})

 request({ // 条件查问
        url: '/api/Gjtype/' + gjtype
      }).then(res => {this.tableData = res.data})


 request({ // 增加
        url: '/api/Gj',
        method: 'POST',
        data: {
          'id': 0,
          'method': this.method,
          'text': this.content,
          'type': this.value
        }
      }).then(res => {console.log(res)
        if (res.status === 201) {this.open1()
          console.log('胜利')
        } else {this.open4()
          console.log('失败')
        }
      }).catch(console.error.bind(console)) // 异样


request({// 更新
        url: '/api/Gj/' + this.id,
        method: 'put',
        data: {
          'id': this.newinfo.id,
          'method': this.newinfo.method,
          'text': this.newinfo.text,
          'type': this.newinfo.type
       }
      }).then(res => {if (res.status === 204) {this.open1()
          console.log('胜利')
        } else {this.open4()
          console.log('失败')
        }
      }).catch(console.error.bind(console)) // 异样 
正文完
 0