建立一个js文件https.js
引入axios和qs

import axios from 'axios';
import $qs from 'qs'

配置个地址以后只需传入地址后缀即可地址默认为以下地址

axios.defaults.baseURL ='https://www.easy-mock.com/mock';

拦截器上面这个是请求拦截器,请求之前处理,下面这个是响应后的拦截器,响应后处理

axios.interceptors.request.use(
  config => {
    config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded'
    }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)

然后是请求函数

export default {
  post(url,data={}){
    return new Promise((resolve,reject) => {
      axios.post(url,$qs.stringify(data))
        .then(response => {
          resolve(response.data);
        },err => {
          reject(err)
        })
    })
  },
  get(url,params={}){
    return new Promise((resolve,reject) => {
      axios.get(url,{
        params:params
      })
        .then(response => {
          resolve(response.data);
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}

这样就简单封装完了然后引入到main中

import https from './common/https'
Vue.prototype.https=https

然后是调用vue组件中直接调用this

this.https.get('/nurse/nurse_infor',{id:1555}).then(res=>{
      console.log(res)
          })
          this.https.post('/nurse/nurse_infor',{id:1555}).then(res=>{
      console.log(res)
          })
Logo

前往低代码交流专区

更多推荐