如何在javascript中从api获取数据时传递用户名和密码凭据?

时间:2018-02-20 04:05:37

标签: javascript authentication wixcode

我正在使用flowroute api并且需要获取数据但不确定如何添加身份验证凭据,即在浏览器中传递查询网址时可以看到 我怎样才能在javascript中传递它。 我正在使用wix平台并添加如下所示的javascript代码

// For full API documentation, including code examples, visit http://wix.to/94BuAAs
import {fetch} from 'wix-fetch';
$w.onReady(function () {
    fetch('https://api.flowroute.com/v2/numbers/available?starts_with=800&limit=3?',{method: 'get',auth:{user:'28288282', pass:'099299292991'}})
      .then( (httpResponse) => {
       console.log(httpResponse.ok);
    if (httpResponse.ok) {

      return httpResponse.json();
    } else {
      return Promise.reject("Fetch did not succeed");



  }
  } )
  .then(json => console.log(json))
  .catch(err => console.log(err));

    //TODO: write your page related code here...



});

将用户名和密码传递给API的正确方法是什么,这样我就可以获得json响应,而不是当前的 401未经授权的响应状态

https://api.flowroute.com/v2/numbers/available?starts_with=800&limit=3 enter image description here

更新我的答案以显示网络呼叫详细信息 要求&响应标头ae在屏幕截图中给出了bwlow enter image description here enter image description here

enter image description here

1 个答案:

答案 0 :(得分:3)

尝试:

fetch('https://api.flowroute.com/v2/numbers/available?starts_with=800&limit=3?', {
  method: 'get',
  headers: {
    "Content-Type": "text/plain",
    'Authorization': 'Basic ' + btoa(username + ":" + password),
  },
})