zoukankan      html  css  js  c++  java
  • axios如何发送Basic Auth

    被VUE和axios折磨的岁月,碰到404和401错误

    axios如何发送Basic Auth认证数据??

    这几天都在搞vue和flask前后端分离的小东西
    后端采用了HTTPBasicAuth加令牌认证
    然后写好后端接口,就用前端axios发送请求

    //前端
    //api.js
    let base = 'http://127.0.0.1:5000/api';
    
    export const requestLogin = params => {
        return axios.post(`${base}/login`, params).then(res => res.data);
    };
    
    //Login.vue
        methods: {
          handleSubmit2(ev) {
            var _this = this;
            this.$refs.ruleForm2.validate((valid) => {
              if (valid) {
                this.logining = true;
                //NProgress.start();
                var loginParams = { name: this.ruleForm2.account, password: this.ruleForm2.checkPass };
                requestLogin(loginParams).then(data => {
                  .....
                });
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          }
        }
    
    //后端
    @auth.verify_password
    def verify_password(name_or_token, password):
        if request.path == "/api/login":
            admin = Admin.query.filter_by(name=name_or_token).first()
            if not admin or not admin.verify_password(password):
                return False
        else:
            admin = Admin.verify_auth_token(name_or_token)
            if not admin:
                return False
        g.admin = admin   
        return True
    

    如上发送数据查看控制台一直报错404
    搜了好久发现是模板问题(这里使用的是vue-admin后台模板)
    需要注释掉mock测试数据才能进行后端接口测试
    关于axios特别说明request failed with status code 404

    然后继续测试,发现又报错401
    看了下代码感觉没什么错误......
    然后就用postman模拟了下请求,发现也是同样的错误

    {
        "error": "Unauthorized access"
    }
    

    然后再看后端代码HTTPBasicAuth.....原谅我很少搞前后端分离
    这个BasicAuth的接口需要特殊的发送请求
    postman中指定auth类型就能发送成功

    postman

    转向axios查找文档发现

    // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
    // This will set an `Authorization` header, overwriting any existing
    // `Authorization` custom headers you have set using `headers`.
    auth: {
      username: 'janedoe',
      password: 's00pers3cret'
    },
    

    于是修改api.js中axios为下面的样子

    export const requestLogin = params => {
        return axios({
            method: 'POST',
            url: `${base}/login`,
            auth: params
        })
        .then(res => res.data);
    };
    

    然后......还是401
    在控制台消息头中发现Authorization的值和postman中的不一样
    只包含了password的值,尝试修改Login.vue中loginParams的name为username
    状态码200K.........................
    en.........好好看文档,好好学习

    咸鱼

    其他url如何post Token???

    不是很清楚正确的姿势是什么,按照后端的代码
    auth认证的方式会首先检验是否为token
    即发送token也是同样的post格式

    export const getAdmin = params => { 
        return axios({
            method: 'GET',
            url: `${base}/admin`,
            auth: {username: params}
        })
        .then(res => res.data);
    };
    
    #params是取得的token
    

    这里有个点就是我按照这个方法请求之后
    还是一直报错401,就是验证失败
    后来才发现是前端post的token含有双引号
    去掉之后就可以正确post了

  • 相关阅读:
    [Unity3D]UI界面之瞄准镜设置说明
    [Unity3d]游戏中子弹碰撞的处理
    [Unity3D]引擎学习之注意事项(持续更新中)
    [Unity3D]添加音效说明
    [Unity3d]3D项目转换为VR项目(暴风魔镜SDK)
    [Unity3d]调试问题之UI/Image不显示
    [Unity3d]向量的过度方法以及拖尾效果
    [Unity3D]脚本生命周期学习
    windows server 2008 应用程序池自动关闭 C:Windowssystem32RpcProxyRpcProxy.dll failed to load
    create a (VSTO) Office 2007 add-in using VS 2012?
  • 原文地址:https://www.cnblogs.com/bay1/p/10982220.html
Copyright © 2011-2022 走看看