javascript atob returning 'String contains an invalid character'

后端 未结 3 1134
抹茶落季
抹茶落季 2020-12-13 09:58

I have an AJAX call getting info out of the Github API. It is returned in base64 encoding but when i try to decode it I get the aforementioned error.

Has anyone run

3条回答
  •  独厮守ぢ
    2020-12-13 10:36

    According to MDN docs, you might need to escape and then decodeURIComponent to handle unicode:

    function utf8_to_b64( str ) {
        return window.btoa(unescape(encodeURIComponent( str )));
    }
    
    function b64_to_utf8( str ) {
        return decodeURIComponent(escape(window.atob( str )));
    }
    
    // Usage:
    utf8_to_b64('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
    b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
    

提交回复
热议问题