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了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM