【问题标题】:How to pass username and password credentials while fetching data from api in javascript?如何在javascript中从api获取数据时传递用户名和密码凭据?
【发布时间】:2018-02-20 04:05:37
【问题描述】:

我正在使用flowroute api 并且需要获取数据但不确定如何添加身份验证凭据,即当我在浏览器中传递查询 url 时可以看到 我怎样才能在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 Unauthorized response status

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

更新我的答案以向您显示网络呼叫详细信息 屏幕截图中给定的请求和响应标头 ae

【问题讨论】:

    标签: javascript authentication velo


    【解决方案1】:

    试试:

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

    【讨论】:

    • 它是Base64编码,这意味着……不太安全
    • @harshal api.flowroute.com 使用称为Basic Authorization 的方案。您需要以以下格式在请求标头中传递凭据:'Authorization': 'Basic ' + <base64 encoded username:password string>btoa 将字符串转换为 base64,就像提到的 @vol7ron 一样。
    • 嗨@agarwalankur85,我尝试在标题中应用授权代码,但它仍然给出错误值。请帮助并让我知道当我在浏览器上尝试时我应该怎么做才能使其正常工作.
    • @harshal - 你能检查你的网络调用,看看请求头是否有授权头吗?还要检查您在此调用的响应中遇到了什么错误?
    • 嗨@agarwalankur85 当我检查响应时,我得到 401 作为 statusCode 和 UnAuthorized 作为 StatusText。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2014-07-18
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多