【问题标题】:How to pass credentials through a fetch request如何通过获取请求传递凭据
【发布时间】:2018-01-28 15:10:20
【问题描述】:

当 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”函数。

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

【问题讨论】:

    标签: javascript node.js rest api fetch


    【解决方案1】:

    您可以使用 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
    });
    

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

    【讨论】:

    • 感谢帕特里克,但它仍然显示弹出对话框。请查看下面更新的代码行 - fetch(url, {method: 'GET', mode: 'no-cors', credentials:'same-origin', redirect: 'follow', agent: null, headers: {"Content -Type": "text/html,application/xhtml+xml,application/xml", "Authorization": "Basic {{token}}" + btoa('user:pass')}, timeout: 5000}
    • 有用的答案!谢谢,帕特里克!是否可能缺少右圆括号?
    • 在节点/打字稿中:凭据不是 RequestInit 的成员
    猜你喜欢
    • 1970-01-01
    • 2012-08-26
    • 2011-10-27
    • 1970-01-01
    • 2017-06-01
    • 2020-10-22
    • 2018-11-10
    • 2021-05-26
    相关资源
    最近更新 更多