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

What could be causing the issue with the conditional validation in my zod and react-hook-form integration?

Hello there! I recently refactored my code and encountered a problem with a conditional field. When the user selects "Yes," an additional field should appear below for them to fill out. However, the issue I'm facing is that when "Yes" is selected, the ...

Displaying JSON data using FormControls in Angular 5

Upon receiving Json values from the server, I am encountering an issue while binding them to respective textboxes. The problem arises as the value in the textbox appears as [object object] <h1>{{title}}</h1> <h3>Catalog</h3> ...

Updating a label dynamically in Angular

QUESTION: Is there a way to dynamically change the text of a label based on a certain condition? Specifically, I want the label to be blank when I'm on a specific route in my App. CURRENT APPROACH: <RadSideDrawer allowEdgeSwipe=&quo ...

Is it necessary for me to set up @types/node? It appears that VSCode comes with it pre-installed

Many individuals have been adding @types/node to their development dependencies. Yet, if you were to open a blank folder in VSCode and create an empty JavaScript file, then input: const fs = require('fs'); // <= hover it and the type display ...

"Exploring Angular 9: A guide to retrieving form data with an array of objects [Revised as of July 29th, 2020

I am encountering an issue with my Angular 9 form code. I am getting the error "ERROR TypeError: Cannot read property 'mobile_number' of undefined" and I need help in resolving this problem. <form (ngSubmit)="processForm()"> & ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...

Initiating the node js service locally

I have been working on a Node.js and Gradle application, but I'm having trouble figuring out how to run it locally. So far, I've done the Gradle build (./gradlew) and NPM run build (compile), with all my dependencies neatly stored in the node_mo ...

The TypeScript reflection system is unable to deduce the GraphQL type in this case. To resolve this issue, it is necessary to explicitly specify the type for the 'id' property of the 'Address'

import { ObjectType, ID, Int, Field } from 'type-graphql'; @ObjectType() export default class Address { @Field(type => ID) id: String; @Field() type: string; @Field() title: string; @Field() location: string; } More informa ...

Master your code with Rxjs optimization

Looking at a block of code: if (this.organization) { this.orgService.updateOrganization(this.createOrganizationForm.value).subscribe(() => { this.alertify.success(`Organization ${this.organization.name} was updated`); this.dialogRef.close(true ...

Encountering the error message 'Object is of type unknown' when implementing the createAsyncThunk function post utilization of Typescript and Redux Toolkit

Currently, I am utilizing Typescript in my React application where Redux Toolkit is being used for state management. The data is being fetched from an Express Api and everything operates smoothly if Redux is implemented without Typescript. However, when in ...

Develop a duplication of the selected text without the need for the clipboard

Looking to implement an internal clipboard with a history feature for my application. Unfortunately, using the clipboard API will require user permission which is not feasible. I want to ensure that formatting such as bold, italics, and strikethrough is p ...

The issue in Angular2 viewmodel where the boolean value fails to update the *ngIf template

I'm seeking assistance with an unusual issue in my Angular2 and Typescript application. Within my template, I have the following HTML utilizing ngIf: <div *ngIf="loading" class="row"> <div class="small-3 small-centered columns" > ...

Angular provides the capability to sort through data using various criteria

I have received an array of objects in a specific format from the server, which may contain more than 2 objects. [ {processId : 1, processName : "process1", country : "germany", companyCode:"IB" , companyHiringType:"FRE", masterClauses:[ {cl ...

The 'autoComplete' property cannot be found within the 'IntrinsicAttributes & InputProps' type

I'm currently utilizing Typescript and React, but encountering the following error: Property 'autoComplete' is not found on type 'IntrinsicAttributes & InputProps'. This is how I am using the component: <Input ...

Exploring the Depths of JSON Arrays within Typescript

I am faced with a challenge in extracting the value of the "id" from the following array of JSON data. The issue lies in the fact that the value is enclosed within double square brackets "[[" which are causing complications in retrieving the desired result ...

Turning HTML into PDF using Angular 10

I am having success generating a PDF from my HTML page when the data is bound to td directly from ts. However, I face issues when trying to bind the value to an input. You can see a working example on Stackblitz. Generating a PDF for my ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...

Convert an interface type variable to a string representation

I'm just starting to learn angular and I'm attempting to convert my response from an interface type into a string so that I can store it in session storage. However, when I try to save them, they are being stored as [object] in the session storag ...

Incorporating Close, Minimize, and Maximize functionalities into a React-powered Electron Application

Struggling with implementing minimize, maximize, and close functionality for a custom title bar in an electron app using React Typescript for the UI. The issue lies within the React component WindowControlButton.tsx, as it should trigger actions to manipu ...

What is the best approach for dynamically accessing or rendering Children within an Angular Component?

I am facing an issue with reusing a component called wrapper with different child components. I found some helpful resources such as this SO question and this article. However, these only address cases where the child component is known in advance. In my s ...