繁体   English   中英

如何使用 axios 请求发送用户名和密码

[英]How can I send username and password with axios request

我在 BambooHr API 上调用一个获取请求,如下所示:

  axios.get
   (`https://api.bamboohr.com/api/gateway.php/companyDomain/v1/employees/2223/photo/large`
    ).then((res)=> {
          console.log("response ",res)
        });
    },

我有 API 密钥和密码。 我怎样才能将它与我的获取请求一起发送。 在 api 中,它们显示如下:

import axios from 'axios';

const options = {
  method: 'GET',
  url: 'https://api.bamboohr.com/api/gateway.php/companyDomain/v1/employees/employeeId/photo/size',
  headers: {
    authorization: 'Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  }
};

axios
  .request(options)
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.error(error);
  });

代替“xxxxxxxxxxxxxx”的是 Api 密钥和密码编码值。 那么我该怎么做我的代码。 在尝试一些事情时,我也遇到了 cors 错误

用这个:

await axios.get(session_url, {
  auth: {
    username: username,
    password: password
  }
});

它应该自己编码成基本格式。

如果那在这里不起作用是另一种选择:

var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.get(session_url, {
  headers: { 'Authorization': + basicAuth }
})

在您的确切情况下,这意味着将选项更改为此:

const options = {
    method: 'GET',
    url: 'https://api.bamboohr.com/api/gateway.php/companyDomain/v1/employees/employeeId/photo/size',
    auth: {
       username: "username",
       password: "password"
    }
};

或这个:

const options = {
    method: 'GET',
    url: 'https://api.bamboohr.com/api/gateway.php/companyDomain/v1/employees/employeeId/photo/size',
    headers: {
        Authorization: `Basic ${btoa(username + ':' + password)}`
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM