0

User can enter different characters for search. For this reason, errors appear when the user enters characters e.g. / or %. How to send the variable search in a get query?

router.get('/get/:search', (req, res) => {
    Label.aggregate(pipeline)
        .then(result => {
            res.json(result);
        })
        .catch(err => {
            res.status(500).send(err);
        });
});

in frontend:

api.get(`${'get'}/${search}`);
3
  • 2
    encodeURIComponent Commented Jun 8, 2021 at 11:17
  • 1
    api.get(`get/${encodeURIComponent(search)}`); Commented Jun 8, 2021 at 11:18
  • Thanks @Chris G and ASDFGerte it works :) Commented Jun 8, 2021 at 11:28

2 Answers 2

0

for it javascript have standard functions encodeURIComponent(param), decodeURIComponent(encodedParam)

on front-end user insert

 const word = 'sear%ch?';

before append word to api url, need encode it.

const encodedWord = encodeURIComponent(word);

on backend after obtain searchWord from url need decode it.

 const word = decodeURIComponent(encodedWord);
Sign up to request clarification or add additional context in comments.

Comments

0

I used solution from @Chris G and @ASDFGerte in comment api.get(`get/${encodeURIComponent(search)}`);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Comments

Your Answer

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