Open In App

How to retain special characters in ExpressJS router URL request ?

Improve
Improve
Like Article
Like
Save
Share
Report

There are some special characters that might be used for some other thing instead of just showing in the URL. If we want to use the special characters in the URL we need to encode them. The following table shows the encoded value of each special character.

Also we can use a method called as encodeURIComponent(“a+b!c+d”)

Setting up environment and Execution:

Front-End:

  • Step 1: Create HTML file, and paste the below code for UI.

    index.html




    <!DOCTYPE html>
    <html>
        <head>
            <title>Page Title</title>
        </head>
        <body>
            <h2>Welcome To GFG</h2>
            <input id="inp" type="text">
            <button onclick="encode()">Go To</button>
      
            <script src="./app.js"></script>
        </body>
    </html>

    
    

  • Step 2: Create JS file, and paste the below code.

    Javascript




    let encode = () => {
        let input = document.getElementById('inp');
        let url = input.value;
          
        url = encodeURIComponent(url);
          
        window.location.href = `http://localhost:5000/search?key=${url}`;
    }

    
    

  • Output: Run index.html File and the output will

Back-End:

  • Step 1: Initialize node.js project

    npm init
  • Step 2: install required modules

    npm install express
  • Step 3: Code in index.js file

    index.js




    const express = require("express");
      
    const app = express();
      
    // Start server on port 5000
    app.listen(5000, () => {
      console.log(`Server is up and running on 5000 ...`);
    });
      
    app.get("/search", (req, res) => {
        res.send(req.query.key);
      
    });

    
    

  • Step 4: Run server node index.js.

Output:

  • User inputting and submitting the value:
  • After getting the value:


Last Updated : 21 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads