版权声明:本文为CSDN博主「LONGLONGAGO_RU」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/LONGLONGAGO_RU/article/details/90290259
1,首先在根目录下新建文件夹utils,然后新建文件request.js
2,在 request.js中统一处理axios请求
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
//创建一个axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests//在跨域请求时发送cookie
// 所有的请求都会带上这些配置,比如全局都要用的身份信息等。
headers: {
'Content-Type': 'application/json'
// 'token_in_header': global_.token,//token从全局变量那里传过来
},
timeout: 5000 // request timeout
})
// response interceptor//响应拦截器
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
// / **
// *如果您想获取标题或状态等http信息
// *请返回响应=>响应
// * /
// / **
// *通过自定义代码确定请求状态
// *这只是一个例子
// *您还可以通过HTTP状态代码判断状态
// * /
response => {
const res = response.data
// if the custom code is not 20000, it is judged as an error.
if (!res.success) {
console.log(res)
Message({
message: res.msg || 'error',
type: 'error',
duration: 5 * 1000
})
// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(res.message || 'error')
} else {
return Promise.resolve(response)
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
3,在根目录下创建api文件夹,此文件夹为接口文件夹
4,然后在api文件夹新建文件user.js,这里放登录接口,不同类别接口创建不同的js文件
import request from '@/utils/request' //引入封装的axio函数
export function login(data) { //请求接口
return request({
url: '/api/ucenter/sys/login',
method: 'post',
data
})
}
export function getInfo(token) {
return request({
url: '/user/info',
method: 'get',
params: { token }
})
}
5,在Login.vue中引用登录接口
import { login } from "../../api/user";
//请求接口
let loginParams = {
loginName: this.ruleForm.username,
password: this.ruleForm.password
};
this.loading = true;
login(loginParams)
.then(res => {
console.log(res.loginUser.sessionId);
this.$router.push('/dashboard');
this.loading = false;
})
.catch(() => {
this.loading = false;
});