Idan E
Idan E

Reputation: 1319

How to pass credentials through a fetch request

I can't pass credentials to avoid of the authentication dialog when GET request is sending as health check to RabbitMQ API. If I pass url with the credentials inside (e.g. http://user:pass@localhost:15672/api/aliveness-test/%2F)

it receives the error below -

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)

If I sending this request without the credentials inside the url it's actually sent the request ok but the authentication dialog pop ups in the UI and it's annoying and not a pretty as well.

The request is below -

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

The trigger to send this request is a "onclick" function inside some HTML file.

I've actually tried every solution I saw in the net, but nothing solves this use case.

Upvotes: 10

Views: 29189

Answers (1)

Patrick Hund
Patrick Hund

Reputation: 20256

You can send your user name and password with fetch using the Authorization header, like this:

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

btoa is a function provided by browsers. If you want to use it on the server side, you can require the btoa npm module to do the job.

Upvotes: 12

Related Questions