使用 Web3.js HttpProvider 调用 API 时如何向 Ankr 提供凭据? [英] How to provide credentials to Ankr when calling the API with Web3.js HttpProvider?

查看:22
本文介绍了使用 Web3.js HttpProvider 调用 API 时如何向 Ankr 提供凭据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问 Ankr API 地址,例如:

I am trying to get access to Ankr API address, which is like:

https://apis.ankr.com/XXXX/YYYY/full/main

通过浏览器访问此链接时,我可以引入我在 Ankr 面板控件上创建的凭据,并且可以成功通过.但是现在我尝试在 Node 上使用 Web3.js 来做到这一点:

When accessing this link by the browser I can introduce the credentials I created on Ankr panel control and I can pass successfully. However now I am trying to do this with Web3.js on Node:

var options = {
    headers: [
        {
            name: 'Authorization',
            value: 'Basic myUsername:myPassword',
        },],};

const web3 = new Web3(new Web3.providers.HttpProvider('https://apis.ankr.com/XXXX/YYYY/full/main', options))

我收到了 401 Unauthorized 错误响应.我认为我的凭据是正确的,因为我可以通过浏览器上的链接访问它们,但在传入标题时它们似乎不起作用.代码有什么问题或缺少什么?

And I receive a 401 Unauthorized error response. I assume that my credentials are right because I could access them by the link on the browser, but not when passing in the header they seem not work. What is wrong in the code or what lacking of?

推荐答案

您需要传递myUsername:myPassword的base64,而不是实际的明文.

You need to pass the base64 of the myUsername:myPassword, not the actual plaintext.

// base64 encoded
value: 'Basic ' + Buffer.from('myUsername:myPassword').toString('base64'),

有关详细信息,请参阅 MDN 文档.

See the MDN docs for more info.

这篇关于使用 Web3.js HttpProvider 调用 API 时如何向 Ankr 提供凭据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆