一:新建util文件夹,并且新建axios.js文件如下图:
import axios from 'axios'
import { Message, MessageBox, Notification} from 'element-ui'
const service = axios. create ( {
baseURL: `http:// ${ process. env. BASE_URL || 'localhost' } : ${ process. env. PORT || 3001 } ` ,
timeout: 10000 ,
headers: { }
} ) ;
service. interceptors. request. use ( config => {
if ( config. url == undefined) {
Notification ( {
title: '警告' ,
message: '请求路径错误,请检查!' ,
type: 'warning' ,
offset: 100 ,
duration: 2000
} ) ;
return false
}
return config
} , error => {
console. log ( error)
Promise. reject ( error)
} )
service. interceptors. response. use (
response => {
const res = response. data
if ( response. status == 200 && res. code === '0000' ) {
return res
} else {
if ( res. code === '401' ) {
Message. warning ( '登录过期,请重新登录!' )
} else {
Message. error ( res. msg)
}
}
} ,
error => {
console. error ( 'err:' + error)
if ( error. request. status == '401' ) {
Message. warning ( '登录过期,请重新登录!' )
} else if ( error. request. status == '404' ) {
Message ( {
message: '错误的请求!' ,
type: 'error' ,
duration: 5 * 1000
} )
} else if ( error. request. status == '500' ) {
Message ( {
message: '服务器异常!' ,
type: 'error' ,
duration: 5 * 1000
} )
} else {
Message ( {
message: 'err请求失败' ,
type: 'error' ,
duration: 5 * 1000
} )
return Promise. reject ( error)
}
} )
export default service;
二:创建接口文件并且导入刚才封装的axios文件
import request from '../utils/axios'
export default {
register: function ( data) {
return request ( {
url: ` ${ users} /register` ,
method: 'post' ,
data
} )
}
*
*
*
}
三:组件内调用封装的接口
import userApi from '../../../interface/user'
export default {
data ( ) {
return {
user: ''
}
} ,
async mounted ( ) {
const { data: { user} } = await userApi. getUser ( )
this . user = user
}
}