Utilizing Multer for MERN File Upload

For my project, I am working on creating a Pinterest-like platform where users can upload images. However, I am facing an issue with fetching files from the frontend to the backend using axios. Below is the code for the server:

After testing various solutions, I am unable to pinpoint the exact flaw in the system. The application successfully stores the photo, but the problem arises when trying to transfer data (specifically files) to the backend, as string data can be retrieved without any issues.

const express = require('express');
const app = express()
const mongoose = require('mongoose')
const cors = require('cors')
const Photo = require('./models/Photo')
const multer = require('multer')
//MiddleWare
app.use(cors())
app.use(express.json())

mongoose.connect('', () =>{
    console.log('Connected to DB..')
})

// storage 
const Storage = multer.diskStorage({
  destination: 'uploads',
  filename: (req, file,cb) =>{
    cb(null, file.originalname)
  }
})

const upload = multer({
  storage: Storage,
}).single('testImage')

app.post('/add', async(req, res) =>{


  console.log(req.files)
})

app.listen(3001, () =>{
    console.log('Listening..')
})

On the client-side, the following code is implemented:

/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable react/jsx-no-comment-textnodes */
import React, { useState, useRef } from "react";
import NotificationsIcon from "@mui/icons-material/Notifications";
import AddAPhotoIcon from "@mui/icons-material/AddAPhoto";
import "./Header.css";
import axios from "axios"
...

When uploading an image, the server's console logs "undefined" which raises questions about why this behavior occurs. The output of `console.log(req)` shows detailed information about the incoming request and socket setup.

Answer №1

Have you attempted to log the value of req?

app.post('/add', async(req, res) =>{
  console.log(req)
})

Instead of

axios.post('http://localhost:3001/add',{photo: photo})
, make sure to use the correct signature:
axios.post(url[, data[, config]])

If you are sending a file using POST, it is necessary to utilize an instance of FormData.

const bodyFormData = new FormData();
bodyFormData.append("media", file);
axios.post('http://localhost:3001/add',{file: bodyFormData})

When accessing the server, be sure to reference the correct key based on the value of req. Use req.files

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

Deep-diff JavaScript functions are not permissible for use

In my AngularJS application, I am currently attempting to utilize a JavaScript package. To reference it in my index.html file, I added the following code: <script src="deep-diff-0.3.1.min.js"></script> Furthermore, in my controller, I am usin ...

What is the best way to trigger a useReducer dispatch function from a different file that is not a React component, without relying on Redux?

In my project, I have a function component that shows a game board named "EnemyBoardComponent.tsx" const enemyBoardReducer = (state:number[][], action:Action)=>{ switch(action.type){ case "update": { return EnemyBoard.getGrid(); ...

How can I utilize the color prop in the theme file to style new variants more comprehensively with MUI theming?

I am working on creating a custom variant for an MUI button where the color specified in the color prop should be applied as both the border and text color. While the MUI documentation offers a suggested approach, it requires addressing each available col ...

What are some ways to implement Node.js within Netsuite?

Recently, I've been exploring Netsuite and I'm curious to learn about the feasibility of integrating Node.js or npm modules into a SuiteScript or Suitelet. Is it possible? I have a specific aim in mind - to utilize some npm modules within Netsui ...

Issue with Select component in Material UI v5 where changing the border to none does not function as expected

I am currently utilizing NextJs with material ui v5 and attempting to set {border: none} for the Select component from mui. However, I am facing issues as it does not seem to work. To tackle this problem, I have decided to apply the sx prop object, conside ...

Transferring information from HTML to React and Redux

Currently, the backend server is generating an HTML page that includes a javascript object named MY_DATA and the root element for the React/Redux app: <script> MY_DATA = { foo: 'bar' } </script> <div id="app"></div> ...

What is the best way to write an SQL query to safely insert a record into a table with a dynamic name?

I'm working on a function that can insert a record into a table in PostgreSQL. The catch is that the table name needs to be a parameter for the function, and the column names are determined dynamically. To ensure protection against SQL Injection, I am ...

When integrating react-router 5 and redux 7, there is an issue where the state is not being reset when navigating to a new route using react-router's <Link

My current setup includes the following versions: `"react-router": "^5.2.0",` `"react-router-domreact-router": "^5.2.0",` I'm unsure if my setup is compatible with React-router 5 as I was using a version prior ...

What could be causing a hydration error when utilizing a table in Next.js?

When attempting to use the tr tag in my code, I encountered an error message that reads: Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. import React from 'react' import {useS ...

Setting up package-lock.json as the definitive source of dependencies truth

I had a similar question to the one asked on Stack Overflow about package.json and package-lock.json (in summary; "what's the difference between package.json and package-lock.json?") and found some insightful answers there. However, I still have some ...

Out of the blue, my session stopped functioning

I am encountering a major issue with sessions. I am working on developing an application using "Redis" in node.js along with various libraries such as express. However, I have run into a problem where the sessions are no longer functioning properly. Desp ...

"What is the best way to apply multiple filters to an array in a React

Is there a way to incorporate dropdown menus along with search text input for filtering an array in React? I would like to give users the option to select a location and then search for specific results within that location. Any suggestions on how to ach ...

"Starting npm in React.js doesn't seem to have any effect

Currently using Mac OS Catalina and Node 12.13.1, I am facing difficulties launching my React app. Upon entering $ npm start in my VS Code terminal, there is no response - no errors or problems encountered. In an effort to resolve this issue, I have atte ...

Make sure Node.js is flushing writes to child processes

To initiate a child process, I use the following code snippet: var child = require('child_process'); var proc = child.spawn('python', ['my_script.py', '-p', 'example']); In addition, I configure data hand ...

What are some alternatives for integrating React production build files apart from utilizing Express?

Is there a way to integrate React into my library using the HTTP module? I'm trying to figure out how to recursively send static files. Specifically, I want to include the build folder from the React production build, but I'm not sure how to go a ...

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

What causes the discrepancies in folder structure between Hexo in development and production environments?

I'm a beginner when it comes to nodejs and I have a question about a blog system built in nodejs called hexojs. The file structure for this blogging framework during development looks like this: https://i.stack.imgur.com/VdWbF.png, The main source c ...

Having trouble installing Ionic?

Can someone please help me with my installation issue regarding Ionic? I've tried installing it with admin rights, but still facing problems. My installation steps are as follows: npm uninstall ionic -g npm uninstall cordova -g npm cache clean npm ...

Utilizing MongoDB to create time-based event triggers

I am working on a front-end application using Angular and a back-end system powered by Express.js. My goal is to have notifications displayed on the front end based on meetings scheduled at specific times. For example: If there is a meeting scheduled f ...

How can one assess a list in clojurescript?

If I have the following list defined: (def defining-list `(def one 1)) How can I execute defining-list so that one is set to 1? (in clojurescript) EDIT: To give a broader context of my goal and prevent getting stuck in an X/y problem. I am attemptin ...