Axios POST 到 Mailchimp API:HTTP 身份验证不起作用

R. *_*sch 8 javascript http-headers mailchimp axios mailchimp-api-v3.0

我正在尝试向我的 mailchimp 帐户发出 axios 请求。但它似乎不起作用。我不能让它授权我 - 我在这里做错了什么?我一直在关注本教程:其中说:

API 有 2 种身份验证方法:HTTP 基本身份验证和 OAuth2。最简单的身份验证方法是使用 HTTP 基本身份验证。输入任何字符串作为您的用户名,并提供您的 API 密钥作为密码。您的 HTTP 客户端库应该具有对基本身份验证的内置支持,但这里有一个快速示例,展示了如何使用 curl 中的 --user 选项进行身份验证:

curl --request GET \
--url 'https://<dc>.api.mailchimp.com/3.0/' \
--user 'anystring:<your_apikey>'
Run Code Online (Sandbox Code Playgroud)

所以我实施了:

axios.post('https://us1.api.mailchimp.com/3.0/lists/xad81287/members/', {
      auth:
        {
          url: 'https://us1.api.mailchimp.com/3.0',
          user: 'blabla:11231h23123j14bhj1b23j12-us1' //this is my API key
        },
      firstName: 'Fred',
      lastName: 'Flintstone'
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
Run Code Online (Sandbox Code Playgroud)

(我在这里随机更改了 API 内容并列出了名称)

我得到的错误:

选项https://us1.api.mailchimp.com/3.0/lists/afafaf/members/ 401(未授权) dispatchXhrRequest @ xhr.js:178 xhrAdapter @ xhr.js:12 dispatchRequest @ dispatchRequest.js:59 Promise已解决(异步) request @ Axios.js:51 Axios.(anonymous function) @ Axios.js:71 https://us1.api.mailchimp.com/3.0/lists/afafaf/members/:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost:8000 '。响应的 HTTP 状态代码为 401。

Nad*_*yaK -3

尝试这个:

axios({
  method:'post',
  url: 'https://us1.api.mailchimp.com/3.0/lists/xad81287/members/',
    auth: {
      username: 'Fred', // anystring
      password: '11231h23123j14bhj1b23j12-us1' // Your API key
    }
}).then(response => console.log(response)).catch(error => console.log(error))
Run Code Online (Sandbox Code Playgroud)

它对我有用。

要使用 Mailchimp API localhost(这样就不会出现 CORS 错误),请退出 Google Crome 并使用以下命令将其打开:

open -a Google\ Chrome --args --disable-web-security --user-data-dir=""
Run Code Online (Sandbox Code Playgroud)