What is the best way to deliver static files in nestjs?

I am working on a project using NestJS, and I have an uploads folder in the root directory of the site where files with various extensions are stored. How should I go about processing these files?

Here are some example file paths:

http://localhost:7777/uploads/audio/85/0.mp3

http://localhost:7777/uploads/movie/85/0.mp4

When attempting to access these files, I encounter the following error:

{ "statusCode": 404, "message": "ENOENT: no such file or directory, stat 'G:\myproject\uploads\index.html'" }

In my App.module file, I followed the instructions from the Nest documentation:

import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
   imports: [
     ServeStaticModule.forRoot({
       rootPath: join(__dirname, '../../../', 'uploads'),
     }),
     UsersModule

In my Main.ts file, I have the following setup:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './App/app.module';
import { ConfigService } from '@nestjs/config';
import { ValidationPipe } from '@nestjs/common';


async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);
  const port = configService.get('PORT'); 
  app.enableCors();
  app.useGlobalPipes(new ValidationPipe()); 
  await app.listen(port);
}
bootstrap();

Answer №1

It appears that the code is searching for the uploads folder within the existing uploads directory.

To address this, you can explicitly specify the URL prefix as shown below:

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', '..', 'uploads'),
      // Specify NestJS to serve the files under ~/uploads/
      serveRoot: '/uploads/',
    }),
  ],
})
export class AppModule {}

Update

Upon running the mentioned repository and adding a console log, it seems that the code is attempting to access the uploads directory under the dist folder, which could be causing another issue.

https://i.sstatic.net/RXV2z.png

Update 2

I have successfully resolved the issue in the repository by making two changes:

  • Including an additional .. to handle the presence of the dist folder
  • Crucially, relocating the code execution to a factory method

Here is the updated code:

ServeStaticModule.forRootAsync({
  useFactory: () => {
    const uploadsPath = join(__dirname, '..', '..', '..', 'uploads');
    return [
      {
        rootPath: uploadsPath,
            serveRoot: '/uploads/',
          },
        ];
      },
    }),

Outcome:

https://i.sstatic.net/6yg6x.png

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

Having trouble parsing the BODY of a NodeJs JSON post request?

I've been working on creating a basic API using nodeJS, but I've run into a problem while trying to post data. Below is my app.js file: const express = require('express'); const feedRoutes = require('./routes/feed'); const ...

Is there a way to reverse the upside-down text generated by OffscreenCanvas.getContext().fillText()?

When using OffscreenCanvas.getContext().fillText() to generate text and then OffscreenCanvas.transferToImageBitmap() to create a map, I noticed that the text appeared flipped upside down when applied as a texture in a threejs project. The image clearly sho ...

Executing a PHP function within the same file using AJAX: A step-by-step guide

I've been exploring online tutorials to learn about ajax as it's a new technology for me. My main goal is to understand how to utilize two functions, create() and population(), in a php file. The create() function generates a form like this: ma ...

Creating a Sticky Table Header with Dynamic Height in React using Material-UI

I am currently utilizing the Material-UI library in React to present a table on my webpage. My goal is to have a sticky header on the table without specifying a fixed height, allowing it to scroll along with the page. However, the code snippet provided doe ...

Creating a personalized script in ReactJS: A step-by-step guide

If I have already built a component with Google Chart in ReactJS, and I want to implement a feature that allows the Legend to show/hide data using a JavaScript script provided here, how and where should I integrate this code to work with my chart? Here is ...

Tips for setting up a range slider for decimal numbers

I have implemented the following code for a range slider. It works perfectly fine for integer values like 1 and 100, but I am facing issues when trying to use decimal values. I attempted to substitute 1 with 0.1 but it did not yield the desired result. ...

How to Fetch Byte Image with Ajax and Display it on the Client Side in ASP.Net MVC

After converting an image to bytes, I am facing the challenge of displaying the byteImage in a browser. I have two sets of data, one being the Image ID and the other being the Image_name, which are displayed in a table. However, I am unable to display the ...

Enhanced password encryption on the client side using jQuery ajax and PHP [advanced technique]

I found a solution here on how to encrypt data in javascript and decrypt it on the server side. I am encountering an issue while trying to implement this with my ajax form submission. I attempted to integrate it into my code snippet below, but it's no ...

The NodeJS API has ceased to retrieve any results from the SQL Server after being executed 11 times

I encountered an issue with a function in my app.js file, which connects to SQL Server to retrieve a recordset. However, after running this function 11 times, it stops functioning. var config = require('./dbconfig'); const sql = require('ms ...

Using TypeScript generics with the `keyof` operator may result in rejection

I created a custom method using the RXJS library which looks like this : function Subject<T>(t: T):T { return t; } In addition, I defined an interface that specifies the structure of my application values. Additional keys can be added to this i ...

derive values from radio group inputs

Attempting to compute a selection value based on a radio group and values from additional fields. Any input in the 'Name' field contributes a value to the Total. The value from the radio group needs to be added to this total. Below is the HTML co ...

Retrieve the attribute of object i using Javascript

Despite my efforts, I have not been able to achieve success. Is there a way for me to dynamically access the value i.MoveTo in order to apply logic directly to that specific value? I have an array of objects similar to the following structure, with proper ...

Steps for integrating ECTJS views into LocomotiveJS

I have a typical setup of Locomotive JS and I am looking to integrate ECTJS for views. The installation of ECTJS was successful using the command below: npm install ect --save Below is the controller I am using: var locomotive = require('locomotive ...

Switch up the box-shadow color with ColorThief!

Is there a way to adjust this script to change the box-shadow color of #player1? <script type="text/javascript> $(window).ready(function(){ var sourceImage = document.getElementById("art"); var colorThief = new ColorThief(); var color = ...

How can I cancel or reset a timeInterval in AngularJS?

In my project demo, I have implemented a feature that fetches data from the server at regular intervals using $interval. Now, I am looking for a way to stop or cancel this process. Can you guide me on how to achieve this? And if I need to restart the proce ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

Managing scroll position based on media queries in JavaScript

I'm currently working on implementing a fade-in/out effect on scroll for a web project. In my JavaScript code, I need to specify a certain value for the scroll position, such as an offset, to trigger the effect. The issue: The offset value may not ...

Using Javascript to merge the components of a multidimensional array

I'm currently working on a project that involves combining elements from a multidimensional array to create different combinations. For example, if I have the following array: var array = [ ['a'], ['1', '2', ...

Tips for Using Multiple Axios Calls within a UseEffect Hook Without Triggering Errors

I require 3 instances of axios: To identify the token and determine which user is logged in. This will provide a "userid" to pass for other axios endpoints To retrieve the list of orders: returns an array containing the order history of the user To fetch ...

Issue: NG0204: Unable to find solutions for all parameters in NzModalRef: (?, ?, ?)

I'm currently working on an Angular project utilizing the NZ-Zorro library, and I'm encountering difficulty understanding which parameters are causing issues with NzModalRef when attempting to run the test code coverage. The error message display ...