Express 4.14.1 experiencing issues with URL rewriting

I have come across several Stack Overflow posts suggesting that to rewrite a URL in Express 4, one would need to implement something similar to the code below:

router.use('/one/:someId', (req, res, next) => {
    req.url = `/two/${req.params.someId}`;
    next();
});

router.get('/one/:someId', (req, res) => {
    res.send("reached /one/:someId");
});

router.get('/two/:someId', (req, res) => {
    res.send("reached /two/:someId");
});

However, upon testing this approach, not only does the URL fail to change as expected to "/two/some integer", but it also leads to a 404 - Not Found error page that I have configured in my application file.

These routes are located in a separate router file, and I even attempted setting the URL to:

req.url = `/routerPath/two/${req.params.someId}`;

but the outcome remains unchanged.

What could I possibly be overlooking?

Appreciate any insights you can offer.

Answer №1

There are two types of redirects that you should be aware of:

  • Internal redirects occur on the server side without the client's knowledge. They are there to make your server programming easier but are not always necessary - you could use a helper method called by all endpoints instead.
  • HTTP redirects tell the client (like a web browser) to visit a different URL. If you anticipate the URL change, this is the type of redirect you need.

To implement this, simply use res.redirect, ensuring special characters are encoded properly:

router.get('/one/:someId', (req, res) => {
    res.redirect(`/two/${encodeURIComponent(req.params.someId)}`);
});

router.get('/two/:someId', (req, res) => {
    res.render("reached /two/:someId");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node js does not support iteration for DirectoryFiles

I am currently working on a program aimed at mapping all the json files within a specific directory. As I am new to JavaScript, this inquiry may not be ideal or obvious. Here is my code: const fs = require('fs'); const { glob } = require('gl ...

A guide to finding the mean in Angular by utilizing JSON information

import { Component, OnInit } from "@angular/core"; import { MarkService } from "../app/services/marks.service"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComp ...

Looking to showcase website HTML code by simply clicking on a banner image?

I am looking to implement a feature where banner HTML code is displayed in a popup on website when the banner is clicked. For instance, an example of a banner could be: <img src="https://myweb.com/images/banners/1.gif"> Upon clicking the banner im ...

Cease the form submission process using Ajax when the input field is blank

I have implemented an ajax code that halts the form submission process if any input value is empty and displays a popup alert. However, I am facing an issue where the process continues even after closing the alert popup. How can I ensure that the process ...

What is the purpose of using the http module to specify the port when the app.listen function already sets the

var express = require("express"); var app = express(); // This code sets the port to 8080 by default, or else it will use the environment-specific port. app.set('port', process.env.PORT || 8080); app.get('/', function(req, res){ r ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...

Is it possible to retrieve the code behind property in JavaScript?

How can I incorporate a C# code behind property into a JavaScript alert(<%= someProperty%>);? I've been trying to make it work but it's not happening. Any suggestions on how to successfully include the codebehind property in the JavaScript? ...

Reference now inactive in an array object no longer exhibiting reactivity

After implementing the following code successfully, we noticed that changing the language updates the text correctly thanks to the ref: const mainNavigationLinks = computed(() => [ { label: context.root.$t('navigationMenu.home') }, { labe ...

Guide to adjusting column width in an XLSX worksheet using Angular4

I am trying to convert HTML into an XLSX sheet in Angular using SheetJS. However, I am encountering an issue where the width of each column is limited to 256 only, and I need to increase it. I have attempted to use ws[!cols] of ColInfo, but I am strugglin ...

AngularJS: Enhancing Date Display and Organization

Looking to change the date format from "Mon Oct 12 2015 00:00:00 GMT+0530 (IST)" to "YYYY/MM/DD" within my controller. ...

using ng-class or ng-style for displaying error messages when validating a text area content

I'm curious about the most effective "angular" method for changing the character count style for validation purposes. I have a text area with a 250-character limit. Instead of restricting users to exactly 250 characters, we want to allow them to excee ...

Showing a JSON file in an HTML page

I've been attempting to showcase a local JSON file on an HTML page. I stumbled upon some information online, but it's causing me quite a bit of confusion. Here is the JSON file I have: { "activities": [ { "name": "C:&bs ...

Controlling the v-model value of a v-select within a v-for loop

I have set up a table of members using a v-for loop, and certain users have the ability to manage other members based on their role. I have implemented some checks to prevent unauthorized roles from intervening, but the full list of checks is carried out o ...

Issue with loading glb file in three.js: The 'format' property is not compatible with this material

When loading a .glb file I created in Blender using three.js, I am encountering an error message three.module.js:7950 THREE.MeshStandardMaterial: 'format' is not a property of this material.. The rest of the content loads correctly. What does thi ...

What is the best way to display the outcome in a popup window?

I am looking to display the result in a pop-up window. Code: <?php $con=mysqli_connect("localhost","root","1234","fyp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = ...

How should you go about including an optional parameter in a function that currently only has one parameter?

I have a function that I need to use in an onClick action as well as other parts of the code. I am attempting to create an optional parameter that returns a class object instead of a false value. import $ from 'jquery' const test = (optionalParam ...

When I type in the TextBox, the CheckBox value should be deactivated if it is unchecked

Whenever I attempt to input text into the textbox associated with my checkbox, the checkbox automatically becomes unchecked. How can I prevent this from happening? <span id="TRAVEL_TYPE_1"><input id="TRAVEL_TYPE_0" type="checkbox" onclick="Update ...

What is the significance of the any type in Typescript?

As I delve into learning Typescript, a question arises in my mind. I find myself pondering the purpose of the any type. It seems redundant to specify it when every variable essentially acts as an "any" type by default. Consider this scenario where the out ...

Retrieve values from the query string (specifically from table rows and cells) for each individual line and display them in

i have some code, see: <script> $$.ready(function() { // Profile Dialog $( "#user-dialog" ).dialog({ autoOpen: false, modal: true, width: 400, open: function(){ $(this).parent().css('overflow', 'visible') ...

Issue with integrating a problem box within a dynamic drawer using React JS and Material UI

https://i.sstatic.net/LraVH.png I recently implemented the code for a Responsive drawer based on the documentation example. The image clearly shows how the content adjusts its height based on the context it's in. However, I want the background of t ...