vue项目中封装的带拦截器的axios请求

1.新建公共请求JS例如api.js;
2.在api.js引入

`import axios from 'axios'
import { Message } from 'element-ui`
const http = axios.create({
  baseURL: '后端接口前缀',
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000
  // request timeout
})
// 设置 post、put 默认请求头 Content-Type
http.defaults.headers.post['Content-Type'] = 'application/json'
http.defaults.headers.put['Content-Type'] = 'application/json'
// request interceptor 请求拦截(请求发出前处理请求)
http.interceptors.request.use(
  config => {
    // do something before request is sent
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
  // 封装get方法
export function get({ url, params }) {
  return new Promise((resolve, reject) => {
    http.get(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

// 封装post方法
export function post({ url, data }) {
  return new Promise((resolve, reject) => {
    http.post(url, data).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}
3.新建页面请求的JS例如http.js
4.在http.js中引入api.js
import { get, post } from './http' // 导入axios实例文件中方法
import { get, post } from './http' // 导入axios实例文件中方法

const server = {
  //带参数的 get 方法
  以下为页面请求的数据接口
  getById(param) {
    return get({
      url: '/role/getById',
      method: 'get',
      params: param
    })
  }
  //不带参数的 get 方法
  getAll() {
    return get({
      url: '/role/getAll',
      method: 'get'
    })
  },
  // post 方法
  login(param) {
    return post({lo
      url: '/role/save',
      method: 'post',
      data: param
    })
  }
}
export default server
5.在页面引入http.js
import apis from '@/api/http'
6.在页面使用api
带参数的请求
 try {
     let data={
          name:this.userName,
          password:this.password
      }
      apis.login(data).then((res)=>{
          Cookies.set('token',res);
          that.$store.commit('login',res)
          that.$router.push({path:'/index'})
      })
  } catch (e) {
      Message({
          message:'服务端错误',
          type: 'warning',
          center:true,
          duration: 1 * 1000
      });
  }
  不带参数的请求
 apis.getAll().then((res)=>{
        
      })


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值