Error: Attempting to access the 'location' property of an undefined variable is not allowed when using res.redirect

Here is a function that retrieves an object from a database and extracts a URL:

async fetchUrl(id: string, redirectFunction: Function) {
    if (!IdExists(id)) {
      throw new Error(`ID ${id} does not exist.`);
    }
    const redirectLocation: string = await prisma.url.findUnique({
        where: { uniqueId: id },
        select: { url: true },
    }).then((data) => {
        return data?.url!;
    });

    redirectFunction('http://' + redirectLocation); 
}

This function is called within the following code segment:

app.get('/:id', async (req, res) => {
    try {
      redirectController.fetchUrl(req.params.id, res.redirect);
    } catch (error) {
      console.error(error);
    } 
});

There seems to be a

TypeError: Cannot read properties of undefined (reading 'location')
error related to the res.redirect method. However, when replacing it with console.log for debugging, the URL is displayed correctly. What could be causing this issue?

Answer №1

When you use this line of code:

redirectController.redirect(req.params.id, res.redirect);

You are passing res.redirect (a function reference) as the second argument. However, only the function is passed, causing the res to be lost when trying to call it later. This results in the method having an incorrect this value when executed, leading to various issues.

This problem can be fixed in multiple ways. One solution is to use .bind():

redirectController.redirect(req.params.id, res.redirect.bind(res));

.bind() creates a stub function that retains the value of res, ensuring that the correct res reference is used when calling the function and maintaining the correct this value inside the function.

Another approach is to create a custom stub function:

redirectController.redirect(req.params.id, (...args) => {
   res.redirect(...args);
});

With this method, your stub function invokes res.redirect() correctly and passes any arguments received from the controller.


To demonstrate this concept, consider the following example:

const obj = {
    greeting: "Hello",
    talk: function() {
        if (this && this.greeting) {
            console.log(`this.greeting is "${this.greeting}"`);
        } else {
            console.log("value of this is wrong");
        }
    }
}

console.log("calling as obj.talk()");
obj.talk();                             // works

console.log("-------------------------");

// function we pass a method to and then call that method
function callTalk(fn) {
     fn();
}

console.log("calling by passing method to another function");
callTalk(obj.talk);                     // doesn't work

// call it using .bind()
console.log("-------------------------");
console.log("calling using .bind()");
callTalk(obj.talk.bind(obj));           // works

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

Is there a method to retrieve Mui state classes easily?

One thing I really appreciate is the way to style mui-components with their class names. I'm curious if there's a method to access state classes like Mui-checked using a variable. Let me delve deeper into this: I have a styled component that lo ...

Display the output of a run script within an HTML div element

I am facing a challenge with a button in my HTML file that, when clicked, calls upon the following script: function onShowTest() { $('div#content').html('<script>alert("Hello")</script>'); }; Currently, when I click th ...

Controlling SVG elements within React

Just starting my programming journey and currently diving into building a surf app using React JS. For the landing page, I want to display location pins on an image of a coastline. These pins should be clickable, leading users to detailed information about ...

Service failure occurs due to the inability to inject a factory

I've been working on an angular seed project that includes services and a factory. Specifically, my companyService relies on a factory named company. However, I've encountered an issue when trying to inject company into companyService, resulting ...

What is the best approach for managing caching effectively?

My SPA application is built using Websocket, Polymer, ES6, and HTML5. It is hosted on a Jetty 9 backend bundled as a runnable JAR with all resources inside. I want to implement a feature where upon deploying a new version of the JAR, I can send a message ...

Error message received while converting webm video to images using Kagami/ffmpeg.js: Unable to locate an appropriate output format for '%04d.jpg'

These are the current versions: node v12.9.1, npm 6.10.2, [email protected] Repository: https://github.com/Kagami/ffmpeg.js The code in decode.js looks like this: const fs = require('fs'); const ffmpeg = require('ffmpeg.js'); c ...

Tool tips not displaying when the mouse is moved or hovered over

I have customized the code below to create a multi-line chart with tooltips and make the x-axis ordinal. However, the tooltips are not displaying when I hover over the data points, and I want to show the tooltips only for the data in the variable. https:/ ...

Using HTML5 Canvas to draw intersecting polygons

Recently, I came across a polygon drawing function that caught my attention: Polygon.prototype.draw = function(ctx) { ctx.save(); ctx.beginPath(); var v = this.vertices[0] ctx.moveTo(this.position.x + v.x, this.position.y + v.y); var i ...

Retrieving Ajax Data Using C#

I am struggling to send data through Ajax to a C# file. Whenever I check the received data, it always comes back as null. Could there be an issue in my code? Javascript file $(".save").click(function () { var ss = "Helloo!"; $.ajax({ typ ...

Creating Production Files for Web using RxJs and TypeScript

I am interested in developing a JavaScript Library using RxJs (5.0.0-Beta.6) and TypeScript (1.8.10). My TypeScript file is successfully compiling. Below are the files I have: MyLib.ts: /// <reference path="../../typings/globals/es6-shim/index.d.ts" ...

Tips for preventing hcaptcha from displaying image challenges during web scraping with puppeteer

When I attempt to scrape a website, the process of passing the captcha can be unpredictable. Sometimes, after clicking on the captcha checkmark, I am presented with images to solve the captcha. Other times, it simply passes me through without any further a ...

Struggling to receive information from a third-party API using a token in a React application

Currently, I am attempting to retrieve data from a third-party API. While it functions properly on Postman, I am striving to successfully make a request and access the data within my React project. The public API in question is: https://api.securityscorec ...

A guide on handling POST response body parsing in NodeJS

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.get("/", function(req, res){ res.sendFile(__dirname + "/index.html"); }); app.post("/", function(r ...

Guide on exporting data from ejs files to a pdf file using pdfkit in a node js environment

Below is the code from my result.ejs file: <div style="width: 50%; margin: auto;"> <table class="table"> <thead> <tr> <th>SUBJECT</ ...

Error with Bootstrap 4 tabs and JavaScript AJAX implementation

I have implemented Bootstrap 4 tabs to showcase content fetched through an AJAX call. However, I encountered an issue upon completion of the call. The error message displayed is: Uncaught TypeError: $(...).tab is not a function The tabs are initially hi ...

Tips on patiently awaiting the completion of resource loading

Seeking guidance from AngularJS experts as I develop an AngularJS application with a control suite comprising a loading screen and a showing screen defined in HTML. The data that needs to be manipulated is stored in JSON files, like the one below: { "St ...

Upon loading the page on a mobile device, simply scroll down to locate the div positioned at the center of the page

How can I make my website automatically scroll to the middle of the page or to a specific div located in the middle of the page when viewed on a mobile device? I have attempted the following code, but it is not functioning and throwing an error: if ($(wi ...

Transforming HTML into a Console Experience (Angular 16)

I'm experimenting with creating a console/CLI style experience using HTML. The goal is to have the input fixed at the bottom of the window, while commands and output rise up from the bottom and eventually disappear off the top of the screen, enabling ...

Utilizing aria-role in Material UI's <Icon> component for enhanced accessibility

I've been using Material UI's <Icon /> component and came across a reference in their documentation about being able to use role="img", which is mentioned here: https://material-ui.com/components/icons/#semantic-svg-icons. However ...

What is the best location for data validation in Express (and MySQL)?

As I delve into learning MySQL through building a REST API with Express, I've made the decision to validate data on the server rather than in the database. But the question that arises is, WHERE on the server should this data validation take place? S ...