axios封装

·  阅读 197
  • 1、创建request.js 配置axios
import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/cookie'

//axios.defaults.withCredentials=true

const service = axios.create({
  baseURL: process.env.baseUrl,
  withCredentials: true,  // 允许携带cookie
})

//添加请求拦截器
service.interceptors.request.use(
  config => {
    config.headers['token'] = getToken()
    return config
  },
  error => {
    console.log(error) 
    return Promise.reject(error)
  }
)
//添加响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 20000) {  //请求不正确
      Message({
        message: res.message || '服务器错误',
        type: 'error',
        duration: 2000
      })
      return Promise.reject(new Error(res.message || 'Error'))  //改变promise状态
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) 
    Message({
      message: error.message,
      type: 'error',
      duration: 2000
    })
    return Promise.reject(error)
  }
)

export default service 
复制代码
  • 2、创建api.js封装请求
import request from '@/utils/request'

export function login(data){  //登录
    return request({
        url:'/user/login',
        method:'post',
        data
    })
}

export function loanCreate(data){  //贷款申请
    return request({
        url:'/loan/create',
        method:'post',
        data
    })
}
复制代码
  • 3、使用
...
import {login} from '@/api'
import {setToken,getToken,removeToken} from '@/utils/cookie'
...
login(this.form).then(res=>{
  console.log(res);
  setToken(res.data.token);  //保存token到cookie
  this.$router.push('/home')   //跳转
})
...
复制代码
分类:
前端
标签:
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改