gpt4 book ai didi

javascript - 如何通过获取请求传递凭据

转载 作者:数据小太阳 更新时间:2023-10-29 06:09:48 24 4
gpt4 key购买 nike

当 GET 请求作为健康检查发送到 RabbitMQ API 时,我无法传递凭据以避免身份验证对话框。如果我传递带有凭据的 url(例如 http://user:pass@localhost:15672/api/aliveness-test/%2F)

它收到以下错误 -

rabbitCol.js:12 Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials: http://user:pass@localhost:15672/api/aliveness-test/%2F
at rabbitColChecking (rabbitCol.js:12)
at allReqInt (allReqInt.js:5)
at HTMLAnchorElement.onclick ((index):108)

如果我在没有 url 中的凭据的情况下发送此请求,它实际上发送了请求,但 UI 中会弹出身份验证对话框,这很烦人,也不是很好。

请求如下-

var fetch = require('node-fetch');

async function rabbitColChecking() {
let index;
const hostsRB = ['http://user:pass@host1:15672/api/aliveness-test/%2F', 'http://user:pass@host2:15672/api/aliveness-test/%2F', 'http://user:pass@host3:15672/api/aliveness-test/%2F', 'http://user:pass@host4:15672/api/aliveness-test/%2F];
let lengthVal = hostsRB.length;
for(let hostIndxRB = 0; hostIndxRB < lengthVal; hostIndxRB++) {
index = hostIndxRB;
let url = hostsRB[hostIndxRB];
fetch(url, {method: 'GET', credentials:'same-origin', redirect: 'follow', agent: null, headers: {"Content-Type": "text/plain"}, timeout: 5000}
).then(function (hostindxRB, res) {
handleLedResponseRB(res, hostindxRB);
}.bind(null, hostIndxRB));
await sleep(500);
}
}

发送此请求的触发器是某个 HTML 文件中的“onclick”函数。

我实际上已经尝试了我在网上看到的所有解决方案,但没有解决这个用例的问题。

最佳答案

您可以使用 Authorization header 通过 fetch 发送您的用户名和密码,如下所示:

fetch(url, {
method: 'GET',
credentials: 'same-origin',
redirect: 'follow',
agent: null,
headers: {
"Content-Type": "text/plain",
'Authorization': 'Basic ' + btoa('username:password'),
},
timeout: 5000
});

btoa 是浏览器提供的函数。如果你想在服务器端使用它,你可以要求 btoa npm 模块来完成这项工作。

关于javascript - 如何通过获取请求传递凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45781924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com