0

I am trying to encode a variable from a http parameter to base64 using node.js and buffer.

My code:

var http = require("http");
var url = require("url");

http.createServer(function(req, res) {

  var parsedUrl = url.parse(req.url, true);
  var queryAsObject = parsedUrl.query;
  var urlEncodeString = new Buffer(queryAsObject).toString('base64');

  console.log(urlEncodeString);

  res.end(urlEncodeString);

}).listen(8020);

console.log("Server listening on port 8020");

URL used: http://127.0.0.1:8020/?test=testtxt

The queryAsObject returns { test: ‘testtxt’ }

Is there a way to use the Buffer to read the variable queryAsObject and encode it with base64 ?

I have spent a good amount of hours searching for ways to make the buffer accept this variable, but I can not find a way that works.

1 Answer 1

1

You need to JSON.stringify() your object first.

Change:

var urlEncodeString = new Buffer(queryAsObject).toString('base64');

to:

var urlEncodeString = new Buffer(JSON.stringify(queryAsObject)).toString('base64');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.