Axios实现登录请求
Axios简介
基本使用
安装:npm install axios
全局引用: import axios from 'axios'
基本使用:
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
实现登录请求
import axios from 'axios'
// 配置请求根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
//拦截器,将没有token的路由拦下
axios.interceptors.request.use(config => {
// console.log(config)
config.headers.Authorization = window.sessionStorage.getItem('token')
return config
})
Vue.prototype.$http = axios
登录逻辑
login () {
//校验数据
this.$refs.loginFormRef.validate(async valid => {
if (!valid) return
//post请求接口,返回数据到data
const { data: res } = await this.$http.post('/login', this.loginForm)
//通过状态码判断
if (res.meta.status !== 200) return this.$message.error('登陆失败')
this.$message.success('登录成功')
// console.log(res)
window.sessionStorage.setItem('token', res.data.token)
this.$router.push('/home')
})
}
路由守卫
在路由发送之前,判断
如果是login
路由,则放行
否则查看是否存在token
,不存在token
的话,跳转到login
页面
// 路由守卫
router.beforeEach((to, form, next) => {
if (to.path === '/login') return next()
const tokenStr = window.sessionStorage.getItem('token') //
if (!tokenStr) return next('/login')
next()
})