Base62 with fetch

Encodes and decodes using external API call with fetch()

by Mika Tuupola

HTML

<p id="encoded">Encoding...</p>
<p id="decoded">Decoding...</p>
<p id="error"></p>

JavaScript

/* http://base62.net/ */

fetch("https://api.base62.io/encode", { 
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({data: "Hello world!"}),
    mode: "cors"
}).then(function(response) {
    if (response.ok) {
        return response.json();
    } else {
        throw new Error("Could not reach the API: " + response.statusText);
    }
}).then(function(data) { 
    document.getElementById("encoded").innerHTML = data.encoded;
}).catch(function(error) {
    document.getElementById("error").innerHTML = error.message;
});

fetch("https://api.base62.io/decode", { 
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({data: "T8dgcjRGuYUueWht"}),
    mode: "cors"
}).then(function(response) { 
    if (response.ok) {
        return response.json();
    } else {
        throw new Error("Could not reach the API: " + response.statusText);
    }
 }).then(function(data) { 
    document.getElementById("decoded").innerHTML = data.decoded;
}).catch(function(error) {
    document.getElementById("error").innerHTML = error.message;
});