matthew-andrews / isomorphic-fetch

Isomorphic WHATWG Fetch API, for Node & Browserify
MIT License
6.95k stars 289 forks source link

How do you write a curl -u call in isomorphic-fetch? I've been trying for awhile now. #129

Closed rublev closed 7 years ago

rublev commented 7 years ago

I have the following cURL which returns data just fine. I was able to get it working with the request library but I have no idea how to convert this call to a fetch call.

curl -u user@site.com/token:<40charToken> \  
https://company.zendesk.com/api/v2/help_center/articles.json
let request = require('request');

let options = {
    url: 'https://company.zendesk.com/api/v2/help_center/articles.json',
    auth: {
        'user': 'user@site.com/token',
        'pass': '<40charToken>'
    }
};

function callback(error, response, body) {
    if (!error && response.statusCode === 200) {
        console.log(JSON.parse(body));
    }
}

request(options, callback);
rublev commented 7 years ago

Does anybody know how to do this in isomorphic-fetch? Every library but iso-fetch is broken for me when using webpack2 and I can't seem to get this working at all.

paulmelnikow commented 7 years ago

In fetch, to do HTTP Basic auth, you have to set the Authorization header yourself. This Stack Overflow answer explains how to do it.

rublev commented 7 years ago

Welp, btoa did it. I had exactly this code before but without using btoa, so I must have done something wrong with b64, overlooked it, and then entered a rabbithole.

const response = await fetch('https://awd.zendesk.com/api/v2/help_center/articles.json', {
    method: 'GET',
    headers: {
        'Authorization': 'Basic '+btoa('user@site.com/token:token'),
        'Content-Type': 'application/x-www-form-urlencoded'
    },
}).then(res => {
    console.log(res);
    return res.json();
}).then(res => {
    console.log(res)
})

Christ I can't believe it took me this long, I need to find a new field of work.