Stpn
Stpn

Reputation: 6394

Node.js cannot decode string.. Characters garbled (question marks)

I really expected this to just work but...

I am getting a base64 string in the header... I want to encode it to UTF8.

strInit = req.headers['authorization']
buf = new Buffer(strInit.length)
i = 0

while i < strInit.length
  buf[i] = strInit.charCodeAt(i)
  i++    
str = buf.toString()
str2 = new Buffer(str, 'base64').toString()
console.log("AUTH REQUEST :",strInit, buf, str, str2)


AUTH REQUEST : Basic dXNlckBnbWFpbC5jb206cXdlcnR5 
<Buffer 42 61 73 69 63 20 64 58 4e 6c 63 6b 42 6e 62 57 46 70 62 43 35 6a 
62 32 30 36 63 58 64 6c 63 6e 52 35> Basic dXNlckBnbWFpbC5jb206cXdlcnR5 
�"q�͕������������ݕ��

I tried decoding it online and it shows as expected ([email protected]:qwerty)

For example here it works fine: http://www.base64decode.org

What am I missing??

Upvotes: 1

Views: 1354

Answers (1)

Stpn
Stpn

Reputation: 6394

SOLVED: OK, actually I found it ... I had to remove "Basic" from the string so the decoder does not get confused..

So the solution is just:

new Buffer(req.headers['authorization'].replace("Basic ",""),"base64").toString()

This way it works.

Upvotes: 1

Related Questions