vue中axios请求带token

发布时间:2022-11-19 23:44:00 阅读:3344次

在vue中我们是通过axios来请求数据

和ajax很类似

在目前前后端分离的开发模式中,我们通常用token来实现认证

以下为axios请求自带token

import axios from 'axios'
import qs from 'Qs'
axios
    .get('/api/v1/delete?id='+row.id,
            {
                    headers:{
                            Authorization:"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"
                    }
            }
    )
    .then(response => {
            console.log(response);
    })
    .catch(function (error) { // 请求失败处理
            console.log(error);
    });

以下为post方式带token

let data = {"user_name":this.param.username,'password':this.param.password};
axios
    .post('/api/v1/admin/login_by_user',qs.stringify(data),
            {
                headers:{
                    Authorization:"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"
                }
            }
    )
    .then(response => {
        console.log(response.data.status);
        if(response.data.status == 'success'){
            this.$message.success('登录成功');
            localStorage.setItem('ms_username', this.param.username);
            localStorage.setItem('Authorization', 'Bearer '+response.data.data.code);
            this.$router.push('/');
        }else{
            this.$message.error('请输入账号和密码');
            localStorage.removeItem('Authorization');
            console.log('error submit!!');
            return false;
        }
    })
    .catch(function (error) { // 请求失败处理
        console.log(error);
    });

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:vue中axios请求带token 出自老鄢博客 | 欢迎分享