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

Ida*_*n E 5 javascript api rest fetch node.js

当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)
Run Code Online (Sandbox Code Playgroud)

如果我发送此请求而没有凭据内部的凭据,它实际上发送了请求,但是在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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

发送此请求的触发器是某个HTML文件中的"onclick"函数.

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

Pat*_*und 6

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

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

btoa是浏览器提供的功能.如果要在服务器端使用它,可以要求btoa npm模块完成这项工作.