简体   繁体   English

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

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

I am calling a get request on BambooHr API like this:我在 BambooHr API 上调用一个获取请求,如下所示:

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

I have API key and password.我有 API 密钥和密码。 How can I send it along with my get request.我怎样才能将它与我的获取请求一起发送。 In the api they are showing like this:在 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);
  });

In place of "xxxxxxxxxxxxxx" there is Api key and passwords encoded value is coming.代替“xxxxxxxxxxxxxx”的是 Api 密钥和密码编码值。 So how can I do this my code.那么我该怎么做我的代码。 And while trying some things I am getting cors errors as well在尝试一些事情时,我也遇到了 cors 错误

Use this:用这个:

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

It will should get encoded into the basic format by itself.它应该自己编码成基本格式。

If that did not work here is an alternative:如果那在这里不起作用是另一种选择:

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

In your exact case this means changing options to this:在您的确切情况下,这意味着将选项更改为此:

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

or this:或这个:

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