TechTurtle
TechTurtle

Reputation: 3167

How to properly use Buffer.from?

My current code uses Buffer('username:password').toString('base64')

That resulted in deprecated warning which lead to this fix: https://nodejs.org/fr/docs/guides/buffer-constructor-deprecation/

However, after replacing buffer with buffer.from(), getting below error: Invalid character in header content ["Authorization"]

Old code:

headers: { Authorization: 'Basic ' + Buffer(this.settings.NPS_USERNAME + ':' + this.settings.NPS_PASSWORD).toString('base64') },

New code

headers: { Authorization: 'Basic ' + Buffer.from(this.settings.NPS_USERNAME + ':' + this.settings.NPS_PASSWORD, 'base64') },

Upvotes: 0

Views: 3317

Answers (1)

apsillers
apsillers

Reputation: 115980

The second argument to Buffer.from indicates the input format of the first argument. You are telling Buffer.from to expect the input USERNAME:PASSWORD to be a base64-encoded string, but this is wrong: the input clearly is not base64-encoded (not least because it includes a colon, which not a valid base64 character).

Instead, you want to indicate how the input is encoded, possibly utf8, and then separately call toString('base64') as you do in your original code, to produce base64 output:

Buffer.from(USERNAME + ':' + PASSWORD, 'utf8').toString('base64')

Upvotes: 2

Related Questions