The value of the filename property cannot be determined as it is undefined

Hey everyone, I'm currently working on a project using nestjs and reactjs. I encountered an error when trying to add a document that reads: "Cannot read properties of undefined (reading 'filename') in multer.config.ts"

   import { diskStorage } from 'multer';
import * as path from 'path'; // Make sure to add this line to import the path module

export const multerConfig = {
  dest: './uploads',
  storage: diskStorage({
    destination: './uploads',
    filename: (req, file, cb) => {
      const filename = `${Date.now()}_${file.originalname}`;
      cb(null, filename);
    },
  }),
  fileFilter: (req, file, cb) => {
    const filetypes = /pdf/;
    const mimetype = filetypes.test(file.mimetype);
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    if (mimetype && extname) {
      return cb(null, true);
    }
    cb(new Error('Only PDF files are allowed'));
  },
};

Here is the service method:

  async create(createCandidats: CreateCandidats, user: User): Promise<Candidate> {
    const { email, username, documents } = createCandidats;
    const candidate = new Candidate();
    candidate.email = email;
    candidate.documents = documents;
    candidate.username = username;
    candidate.user = user;
    return await this.candidateRepository.save(candidate);
  }
  

And this is the controller section:

@Post()
@Roles(Role.Admin)
@UseGuards(AuthGuard())
@UseInterceptors(FileInterceptor('document'))
 async create(
@UploadedFile() document: Express.Multer.File,
@Body() createCandidats: CreateCandidats,
@GetUser() user: User
): Promise<Candidate> {
console.log("check the documents in express multer",document)
console.log('1===>',createCandidats)
const documentName = document.filename;
console.log('2===>',document.filename)
createCandidats.documents = documentName;

return await this.candidateService.create(createCandidats, user);

I have a POST method set up to upload a pdf document in the backend, which works fine with Postman's form data test. However, I encounter the error "Cannot read properties of undefined (reading 'filename')" when testing it on the frontend xhr.js:247 POST http://localhost:3000/candidates 500 (Internal Server Error)

Answer №1

In the scenario where you are sending a request to your server with an application/json content type (as shown in previous React code), it is important to note that if you are using the FileInterceptor, which relies on multer for body parsing, you will need to send the request as multipart/form-data. This is necessary for correct parsing of the body and for the file to be included in req.file, as expected by @UploadedFile() in Nest.js.

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

Steps to access a Request object within a Controller

I am currently working with Express and Typescript, utilizing Controllers for managing requests. In an attempt to create a BaseController that includes the Request and Response objects for each request, I wrote the following code snippet. However, it see ...

Updating ComboBox Selection in Angular 4

When attempting to populate a combobox with the value from a selected row, only the inputs are loading. This section is part of my page: ` <form class="form-horizontal form-label-left parsleyjs" method="post" data-parsley-priority-enabled="false" n ...

Is it possible to use Firebase auth.user in order to retrieve the signed-in user directly?

As I develop a webapp with NextJS v13.4 and firebase as my backend using the firebase web modular api, I came across a statement in the documentation: "The recommended way to get the current user is by setting an observer on the Auth object." ...

After submitting a multi-image form from Angular, the "req" variable is not defined

I'm currently facing an issue with submitting a form from Angular 7 to a Node backend using Multer as middleware and Express.json() as bodyParser. While the text data is successfully transmitted to the backend, the image fields are appearing empty {}. ...

Error: Observable<any> cannot be converted to type Observable<number> due to a piping issue

What causes the type error to be thrown when using interval(500) in the code snippet below? const source = timer(0, 5000); const example = source.pipe(switchMap(() => interval(500))); const subscribe = example.subscribe(val => console.log(val)); V ...

What could be causing my function to not provide the expected output?

Whenever I try to invoke the function from another part of the code, I encounter an issue where it returns undefined before actually executing the function. The function is stored in a service. login.page.ts: ngOnInit(){ console.log(this.auth.getRole()) ...

Determining the type of a keyof T in Typescript

I am currently working on developing a reusable function that takes an observable and applies various operators to return another observable. One issue I am facing is getting the correct type for the value based on the use of the key. The code snippet bel ...

Importing node_modules in Angular2 using TypeScript

My Angular2 app started off as a simple 'hello world' project. However, I made the questionable decision to use different directory structures for my development environment and the final deployment folder on my spring backend. This difference c ...

Navigating a text input field in a NextJS application

Having trouble with handling input from a textarea component in a NextJS app. This is the structure of the component: <textarea placeholder={pcHld} value={fldNm} onChange={onChangeVar} className="bg-cyan-300" ...

React component showing historical highchart data when navigating through previous and next periods

I developed this element to showcase a Highchart. It's utilized within a dashboard element that I access from an item in a list. It mostly works as intended, but not entirely. When I move to the dashboard for item A, everything functions correctly. H ...

Starting object arrays in Angular 6 using ES6

As someone who is just starting out with javascript, I have encountered a challenge with a nested class structure. Specifically, I am looking to initialize an array of EventDate objects and assign it to 'this.dates' within the CustomerEvents cons ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

What is the best way to display the source code of a function in TypeScript?

I am interested in obtaining the source code for my TypeScript function ** written in TypeScript **. Here is the TypeScript code: var fn = function (a:number, b:number) { return a + b; }; console.log("Code: " + fn); This code snippet displays the Ja ...

What is the process for converting BitmapData from Flash into HTML canvas?

Currently facing a significant challenge as I transition from using Flash to JS. The issue lies in handling SOAP returned data, specifically when dealing with images stored as strings that need to be converted into BitmapData for use in Flash. Despite tryi ...

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

Typescript classes implementing data hydration and dehydration techniques

Exploring ways to share TypeScript classes or interfaces between a React + TS frontend and node + TS backend. Converting class instances into JSON poses a challenge as TS types are removed during compile time. Considering options for defining objects in a ...

Connection established between NextJS and a node backend via a socket

I'm currently working on setting up a basic socket connection between my NextJS client side (running on localhost:3000) and my NestJs server (running on localhost:3003). The code for the server is as follows: ChatGateway.ts import { Subscribe ...

Understanding the complexity of defining the type of a function can be challenging. If you're tasked with a complicated function, determining its type

Let's break it down: Dict is defined as { [key: string]: () => any } The desired return value is represented by X I am attempting to create a type for a function that: Takes in a dictionary Dict T Returns an X Now, X also functions as a functio ...

Utilizing Visual Studio Code for setting breakpoints in Typescript Jasmine tests

Currently, I am in the process of configuring a launch setup in Visual Studio Code for debugging my unit tests. The unit tests are written in Typescript, and both the tests and the corresponding code are compiled into a single js file with a source map. ...

Encountering an Issue with Dynamic Imports in Cypress Tests Using Typescript: Error Loading Chunk 1

I've been experimenting with dynamic imports in my Cypress tests, for example using inputModule = await import('../../__tests__/testCases/baseInput'); However, I encountered an issue with the following error message: ChunkLoadError: Loading ...