The GET API endpoint "download" in express is not able to recognize the requested parameters

I am currently working on setting up an API endpoint named GET, which allows an application to retrieve a file based on its id after authentication from the middleware authenticateUser. However, Express is having trouble recognizing the URL parameter id.

I have attempted adding the parameter in different files. To provide more context, there are two files involved: a router.ts file and a download.ts.

Here is the content of download.ts:

import client from "../config/database"
import { Router, Request, Response } from "express"
import authenticateUser from "../utils/auth"
const router = Router()

router.get(
  "/:id",
  authenticateUser,
  async (res: Response, req: Request) => {
    const fileId = req.params.id
    
    const file = await client.query(
      "SELECT userid FROM files WHERE id = $1",
      [
        fileId
      ]
    )
    if (file.rows[0].userid == req.user.id) {
      res.download("../uploads/" + req.params.id)
      return res.status(200).send()
    } else {
      return res.status(401).send()
    }
  }
)

export default router

And here is the content of router.ts:

import { Router } from "express"

import signup from "./signup"
import login from "./login"
import upload from "./upload"
import download from "./download"
import ping from "./ping"
import new_dir from "./newDirectory"

const router = Router()

router.use("/signup", signup)
router.use("/login", login)
router.use("/upload", upload)
router.use("/download/", download)
router.use("/ping", ping)
router.use("/new_dir", new_dir)

export default router

I have tried adding the id parameter in both router.ts and download.ts, but it was not recognized and remained undefined.

router.use("/download/:id", download)
router.get(
  "/:id",
  authenticateUser,
  // Main function here
)

After reviewing a related question on Stack Overflow, I made some modifications to the code in router.ts:

router.use(
  "/download/:id", 
  (req, res, next) => { // Add a function to assign request params to another variable that can be read by the handler
    req.parameters = {}
    req.parameters.fileId = 2
    next();
  },
  download
)

Despite these changes, the error persisted indicating that the variable was still undefined with no clear solution in sight. The following is the error log retrieved from the terminal:

D:\Websites\picture-upload-download-platform\backend\node_modules\express\lib\router\layer.js:95
    fn(req, res, next);
    ^
TypeError: Cannot read properties of undefined (reading 'fileId')
    at D:\Websites\picture-upload-download-platform\backend\src\routes\download.ts:10:35
    at Layer.handle [as handle_request] (D:\Websites\picture-upload-download-platform\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\Websites\picture-upload-download-platform\backend\node_modules\express\lib\router\route.js:149:13)
    at authenticateUser (D:\Websites\picture-upload-download-platform\backend\src\utils\auth.ts:37:5)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

Despite all my attempts, I have been unable to resolve this issue. My apologies if the question is unclear or incorrectly formatted, as I am still learning how to ask questions effectively.

EDIT: Below is my authentication middleware used for endpoints like upload:

const authenticateUser = async (req: Request, res: Response, next: NextFunction) => {
  const authToken = req.headers.authorization;
  ...
};

Answer №1

Your parameter order is incorrect in your method signature:

async (res: Response, req: Request) => {
    const fileId = req.params.id

It should be

async (req: Request, res: Response) => {
    const fileId = req.params.id

For more information, refer to the Express routing guide

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

Using the connect-flash package to display a flash message on the website

Currently working on learning expressjs and mongodb through various exercises. I am attempting to display flash messages whenever a new item is added, updated, or deleted from the database. Struggling with getting it to work as expected without any errors ...

The expected input should be either an HTMLElement or an SVGElement, but the received input is currently null

Below is the code for a component: function SignUpPage() { return ( <> <h1>Sign Up</h1> <input name="userName" /> </> ); } export default SignUpPage; Testing the component: it("should c ...

Is there a way to ensure that the line numbers displayed for JavaScript errors in Chrome are accurate?

I suspect either my webpack configuration or my npm run dev script are causing the issue, but I'm unsure of what exactly is going wrong. While running my application in development mode, I encounter error messages like: Uncaught TypeError: this.props ...

Removing the unhandledRejection event listener in Node.js Express

In order to manage errors in my Express app that use async/await functionality, I have implemented centralized error handling to ensure appropriate status codes and messages are sent as responses. My current approach is as follows: const handleRejection ...

How can data be transferred from a parent to a child component in Angular?

I'm facing an issue trying to pass the selected value from a dropdownlist in a user interface. I have a parent component (app.component.html) and a child component (hello.component.html & hello.component.ts). My goal is to transfer the option val ...

The Threejs Raycaster detects collisions with objects even when the ray is just grazing the surface

Within my Vue component, I have integrated a threejs scene and I am facing an issue with selecting objects using the mouse. I am currently using the OnPointerDown event and raycaster to locate objects under the mouse pointer. However, it seems like the ray ...

Initiating a GET request to execute an SQL query with specified parameters

Let me provide some background information. I am currently using Angular for the frontend and Express for the backend, while also learning how to effectively utilize both technologies. In my application, there is a parent component that generates a group ...

Utilizing multiple routers in Express middleware for Node.js

How do I successfully display my data from mongoDB that is organized into collections? I am able to access the data individually, but encounter difficulties when trying to retrieve them collectively. Here is an example of how my code is structured: Within ...

What is a more effective approach for managing form data with React's useState hook?

Seeking a more efficient solution to eliminate redundancy in my code. Currently, I am utilizing useState() for managing user data, which results in repetition due to numerous fields. Below is a snippet of my current code: const [lname, setLast] = useState& ...

What is the recommended data type for Material UI Icons when being passed as props?

What specific type should I use when passing Material UI Icons as props to a component? import {OverridableComponent} from "@mui/material/OverridableComponent"; import {SvgIconTypeMap} from "@mui/material"; interface IconButtonProps { ...

Utilizing MakeStyles from Material UI to add styling to a nested element

I was pondering the possibility of applying a style specifically to a child element using MakesStyles. For instance, in a typical HTML/CSS project: <div className="parent"> <h1>Title!</h1> </div> .parent h1 { color: # ...

Having trouble setting up mongodb-memory-server 8 to work with jest

I am currently working on integrating the latest version of mongodb-memory-server with jest on a node express server. While following the guide provided in the mongodb-memory-server documentation (), I encountered some gaps that I am struggling to fill in. ...

Encasing a drop-down menu within a personalized container

I am looking to create a custom HTML element that mimics the behavior of the native <select> element but also triggers a specific update function whenever an attribute or child node is modified. This is essential for incorporating the bootstrap-selec ...

What is the best way to send a 102 Processing status code in Express?

I'm in the process of configuring a new HTTP server to run a lengthy command and return the output of that shell command back to the client. Currently, I am using Express v4.17.1. However, requests from clients are consistently timing out when runnin ...

ExpressJS/EJS autofocus problem with trix

As I work on setting up my blog using NodeJS/Express, I've encountered an issue with the Trix editor while trying to edit a post. The rich text area of the Trix editor automatically focuses, preventing any edits in other text areas on the page. Below ...

Generating Pulumi Outputs for exporting as an external configuration file

I am currently utilizing Cloudrun in GCP and am interested in summarizing the created APIs with API Gateway. To achieve this, a Swagger/OpenAPI v2 document needs to be generated containing the google-generated URLs for the Cloudrun Services. How can I ext ...

Issue with ng-file-upload and Busboy causing upload error on server

I am facing a situation where I need to upload both a .zip file and a .xlsx file to an endpoint simultaneously. On the client side (Angular 1): files.upload = Upload.upload({ url: '/api/files', data: { xlsxFile: xlsxFile, zipFile: zipFile } ...

Verify if TypeScript object contains a specific key dynamically without the need for a custom type guard

Using TypeScript's in keyword allows us to check if an object contains a specific key in a type-safe manner when the key is defined as a string literal: function guardHasTest <Data extends object> ( value: Data ): Data & Record<'te ...

Issue with comparing strings in Typescript

This particular issue is causing my Angular application to malfunction. To illustrate, the const I've defined serves as a means of testing certain values within a function. Although there are workarounds for this problem, I find it perplexing and woul ...

Could there be any issues with the structure of my mongoose schema?

I've been stuck for 3 hours trying to solve this problem. I can't seem to retrieve any data from my document. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var accountSchema = mongoose.Schema({ username: String ...