javascript – Axios:无法使用Basic Auth调用API

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

继承我的代码

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)
  }) 
}

即使我输入了凭据以及正确的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

原始请求看起来像那样

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

我错过了什么?凭借Postman和完全相同的凭据,一切都像魅力一样.即使在Chrome中也是如此.

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

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

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

最佳答案 所以我一直在寻找如何为此做一个帖子的例子,但找不到一个好的帖子.得到它的工作,它看起来像:

const { MAILCHIMP_KEY } = process.env;

const url = "https://us{yourRegionNumber}.api.mailchimp.com/3.0/lists/{yourlistid}/members/";

const client = axios.create({
  auth: {
    username: "yourmailchimpusername",  //This could be your email
    password: MAILCHIMP_KEY
  },
  headers: {
    "Content-Type": "application/json"
  }
});

const mailChimpRes = await client.post(url, {
  email_address: `${email}`,
  status: "subscribed",
  merge_fields: {
    FNAME: `${firstName}`,
    LNAME: `${lastName}`
  }
});
点赞