Skip to content
Advertisement

How to pass a question mark express router api to update sql

I want to update a varchar field (String) using and End-Point Api (Express NodeJS) but I have problem went I pass invalid inputs like question mark.

Express End-Point:

router.get("/updateField/:table/:field/:value/:num/:postid/", function(req, res) {

    connection.query(

        'UPDATE '+ req.params.table +' SET ' + req.params.field +' = '+JSON.stringify(req.params.value) +' where language ='+ req.params.num +' and post_id ='+req.params.postid 

This code work fine:

http://localhost:3001/api/updateField/posts/TITLE/When/1/1

But this NOT WORK:

http://localhost:3001/api/updateField/posts/TITLE/When?/1/1

I send the request from react like this:

fetch(
      "http://localhost:3001/api/updateField/" +
        table +
        "/" +
        field +
        "/" +
        value +
        "/" +
        lenguage +
        "/" +
        post_id
    );

Advertisement

Answer

Use javascript function encodeURIComponent() to escape special characters in URL parameters.

For example try this on your browser console and you’ll get an idea:

console.log(
      "http://localhost:3001/api/updateField/" +
        table +
        "/" +
        field +
        "/" +
        encodeURIComponent(value) +
        "/" +
        lenguage +
        "/" +
        post_id
    );
console.log(encodeURIComponent("When?"));

You will see that “When?” is replaced with “When%3F” in URL. In Node.Js, you’ll receive parameter value as string “When?”.

To know more about encodeURIComponent(), refer to this

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement