Open In App

How to Retain Special Characters in ExpressJS Router URL Request ?

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Retaining special characters in Express.js router URL requests involves ensuring that URLs are correctly encoded and decoded, and configuring your Express application to handle these characters appropriately. Special characters, such as @, #, ?, &, +, etc., need to be properly encoded when used in URLs to ensure they are transmitted correctly and interpreted by the server.

Key Considerations

  • URL Encoding: URLs should be encoded to ensure special characters are represented in a way that is safe for transmission.
  • Express Router Configuration: The Express router should be set up to handle encoded URLs and properly decode them to retain special characters.

Note: Also, we can use a method called as encodeURIComponent("a+b!c+d")

Example: Implementation to design frontend part to retain special characters in ExpressJS router URL request

HTML

<!-- 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>
JavaScript
// app.js

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

Output:

Backend Setup

Step 1: Initialize node.js project

npm init

Step 3: Initialize the NodeJs project inside the myapp folder.

npm init -y

Step 3: Install the necessary packages/libraries in your project using the following commands.

npm install express

Project Structure:

Screenshot-2024-07-01-225555

The updated dependencies in package.json file will look like:

"dependencies": {
    "express": "^4.19.2",
  }

Step 3: Code in index.js file Node

// app.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 to Run Application: Run the application using the following command from the root directory of the project

node index.js

User inputting and submitting the value

After getting the value:


Next Article

Similar Reads