Axios:无法使用基本身份验证调用 API

Rob*_*fel 8 javascript api rest basic-authentication axios

我正在尝试get通过 axios 在 Vue 中发出 CORS请求。到目前为止一切正常,但如果我需要通过基本身份验证进行身份验证,我无法让它工作。

这是我的代码

getData: function() {
  let vm = this; // assign vue instance to vm

  axios.get('url', {
    withCredentials: true,
    auth: {
      username: 'name',
      password: 'pass'
    }
  }).then(function(response) {
    console.log(response)
  }).catch(function(error) {
    console.log(error)
  }) 
}
Run Code Online (Sandbox Code Playgroud)

即使我正确输入了凭据和 url,我也总是收到 401 响应。它看起来像这样。

HTTP/1.1 401 Authorization Required
Date: Wed, 01 Feb 2017 16:23:31 GMT
WWW-Authenticate: Basic realm="'Realm'"
Content-Length: 499
Keep-Alive: timeout=15
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
Run Code Online (Sandbox Code Playgroud)

原始请求看起来像这样

OPTIONS 'url' HTTP/1.1
Host: 'host'
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: GET
Origin: http://localhost:9000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76
Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
DNT: 1
Referer: http://localhost:9000/pages/blog_cc/blog_cc.html
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: de,en;q=0.8
Run Code Online (Sandbox Code Playgroud)

我错过了什么?使用 Postman 和完全相同的凭据,一切都像魅力一样。即使直接在 Chrome 中。

我看到这个问题已经被问过几次了,但是在其他线程上提出的所有答案对我来说都不是解决方案。例如,我无法从节点发出请求。

编辑:我也尝试过使用 vanilla JS 发出请求,但也无济于事。看来问题出在后端。不过,这是我的代码。

let xml = new XMLHttpRequest();
xml.open('GET', api, true);
xml.setRequestHeader('Authorization', 'Basic: ' + btoa(user + ':' + pass));
xml.send();
Run Code Online (Sandbox Code Playgroud)

Jef*_*f L 5

我有同样的经历,我的解决方法是使用以下设置来处理与我们设置的 OAuth 服务器的通信:

axios({
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  method: "post",
  url: REVOKE_URL,
  auth: {
    username: CLIENT_ID,
    password: CLIENT_SECRET
  },
  data: {
    datastuff: actualData
  }
});
Run Code Online (Sandbox Code Playgroud)

在连续几天尝试使用 axios.post 徒劳无功之后,这成功了。

axios版本:0.18.0


the*_*ggs 0

withCredentials: true,如果是跨站点请求,您可以尝试将该选项传递给 Axios 请求。