RectJS & NodeJS : Encode & decode url from client to serve

Viewed 29

const quParams = {sample1: 'one', sample2: 'one+one/two', sample3: 'testing'}

if (Object.keys(quParams).length) {
const api_params = `&${Object.keys(quParams).map(x => `${x}=${quParams[x]}`).join("&")}`
     console.log('api_params>>>>>>>>>>', api_params)
  }

`

const quParam = {sample1 : 'one', sample2: 'one%2Bone%2Ftwo'}

let objKeys = Object.keys(quParam);
let quParamValue = ''
  for (item of objKeys) {
  quParam[item];
    if (item === 'sample2') {
      quParamValue = quParam[item].replaceAll('%2F', '/').replaceAll('%2B','+')
    console.log('quParamValue>>>>>>', quParamValue)
  }
}

`one of the query params of client side url has Special Character in the param(sample2)

https://example.com/endpointService?sample1=one&sample2=one+one/two

When passing this url from client side to server side it is encoded as

https://testing.com/endpointService?sample1=one&sample2=one%2Bone%2Ftwo

When passing this encodedURL to RESTFUL api service, is not giving good response.

How to handle this scenario..

Where and how we have to encode & decode the query value using JS

Client (React JS) >>> Server (Express JS) >>> Restful Service

How to do it without replacing on node js

1 Answers

Most libraries handle this for you so by the time you are sending/getting the request object the params are already encoded/decoded respectively. In case you have to do that by yourself you can use the decodeURI function:

const uri = 'https://mozilla.org/?x=1+ a/ 2';
const encoded = encodeURI(uri);
console.log(encoded);
// expected output: "https://mozilla.org/?x=1+%20a/%202"

try {
  console.log(decodeURI(encoded));
  // expected output: "https://mozilla.org/?x=1+ a/ 2"
} catch (e) { // catches a malformed URI
  console.error(e);
}

check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI

In express, you can retrieve the url and query params in the route handler:

app.get('/api/users/:name', function(req, res) {
  const queryParam = req.query.name // for example
  res.send('Hello ' + req.name + '!');
});

If you are not satisfied and need to get params in a special pattern you may create a custom middleware and parse the query string the way you wish.

Related