What could be causing the multer middleware to fail to work properly?

Within the app.js file, there is a direct route to handle image uploads:

app.post('/upload', upload.single('image'), (req, res) => { res.json({ message: 'pic uploaded' }); });

Posting to /upload successfully uploads the image. However, when using app.use('/phones', phoneRoutes);, the image fails to upload. Can you help me identify the mistake? Both files are identical, yet it only works within app.js.

app.js:

 
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const phoneRoutes = require('./routes/phoneRoute');
const multer = require('multer');

const cors = require('cors');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './images');
  },

  filename: (req, file, cb) => {
    console.log('file: ', file);
    cb(null, Date.now() + file.originalname);
  },
});

const upload = multer({ storage: storage });

//initialize
const app = express();

//middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());

//routes
app.post('/upload', upload.single('image'), (req, res) => {
  res.json({ message: 'pic uploaded' });
});

app.use('/phones', phoneRoutes);

//connect to mongodb
mongoose
  .connect(process.env.MONGO_URI)
  .then(() => {
    app.listen(process.env.PORT);
    console.log('Connected to mongodb: ', process.env.PORT);
  })
  .catch((err) => console.log(err));

phoneRoutes.js:


const router = require('express').Router();
const { createPhone } = require('../controllers/phoneController');
const multer = require('multer');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, '../images');
  },

  filename: (req, file, cb) => {
    console.log('file: ', file);
    cb(null, Date.now() + file.originalname);
  },
});

const upload = multer({ storage: storage });

router.get('/:id', (req, res) => {
  res.json({ message: 'get phone: ' + req.params.id });
});

router.get('/', (req, res) => {
  res.json({ message: ' all Phones' });
});

router.delete('/:id', (req, res) => {
  res.json({ message: 'phone ' + req.params.id + ' is deleted' });
});

router.post('/', upload.single('image'), (req, res) => {
  res.json({ message: 'pic is uploaded' });
});

module.exports = router;

Answer №1

Your message

cb(null, '../pictures');

The path you provided is relative to the current working directory of the Node.js process. To ensure safety and accuracy, it is recommended to adjust the path relative to the directory where the Javascript file galleryRoutes.js is located:

cb(null, __dirname + '/../pictures');

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

In the middleware, the request body is empty, but in the controller, it contains content

Below is my server.js file: import express from "express"; import mongoose from "mongoose"; import productRouter from "./routers/productRouter.js"; import dotenv from "dotenv"; dotenv.config(); const app = expres ...

When I try to deploy to Vercel, I often encounter errors in Next.js that I didn't come across while developing. How can I address these issues pro

Recently, as I began deploying to Vercel, an issue arose where I needed to constantly check for errors during the build process. Strict TypeScript errors and messages like "Can't use <img> tag, please use next/image" kept cropping up after each ...

The recognition of express is an issue in the Bitnami MEANstack environment

Recently, I set up a native installation of Bitnami MEAN stack on my Windows system and followed their tutorial to create a new project. However, when attempting step 3 by running the command express myproject, I encountered an error message stating that & ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

Make sure that the Mongoose save operation is finished before executing the callback function

Encountering a challenge in my initial node app development, where the callback function is triggered before the database write operation is fully completed. The issue arises when an authenticated user visits site.com/model URL. The system checks the data ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

Retrieving modified object values in Node.js - A comprehensive guide

How can I retrieve the modified value of an object? The file index.js is executed before index2.js and here's what my code looks like: var object = { size:'5' }; var setSize = function(size) { object.size = size; } exports.object ...

What is the best way to share Discord conversations on the server?

I've been on a quest for quite some time to figure out how I can send a discord message to my website. After stumbling upon Express, I'm struggling to wrap my head around how to display the data on my site when a discord message event is triggere ...

Error occurs when running gulp-imagemin task

I'm having trouble compressing my images for the production server and encountering an error while running the gulp-imagemin task. Below is the gulp task I am using: gulp.task('images', function(){ gulp.src('builds/development/ima ...

Handling Responses in Node.js using Express

I am completely new to using express (or any JS backend) so please forgive me if this question has already been answered or if it seems silly. I have successfully set up an endpoint. app.get('/hello-world'), async (req, res) => { try { ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

An error occurred when attempting to run the command npm run compile:sass, displaying the message: npm ERR! missing script:

Everything seems to be in place with the sass folders and files, so what could be the issue? I have my package.json file set up correctly with the following code: { "name": "starter", "version": "1.0.0", " ...

Compiling the library with node-gyp and its dependencies

I am searching for a method to simplify the setup process for the Node.js module "libtorrent." My objective is to offer pre-compiled .node files for various architectures, similar to what is done in the fibers module. This approach allows users to instal ...

When Hyperledger Composer module local_connection.json is implemented on Google Compute Engine

After successfully running my hyperledger composer project on localhost, I encountered issues when trying to deploy it to Google Cloud Compute Engine. The project consists of a composer network and a nodejs backend for interacting with the network. I foll ...

Encountered a failure while attempting to substitute environment variables in configuration files with the help of Bash and

Trying to integrate a private NPM module into my application is proving to be quite challenging. I need to configure the NPM access tokens correctly so that third-party tools like Heroku and CI can access and install the module. In my ~/.bash_profile, I h ...

Issues with the w3c validator are preventing proper validation due to an unsuccessful SSL connection attempt

Everything seems to be running smoothly on my website when viewed in the browser. However, when I try to validate it using the W3C validator, I keep encountering an error message. https://i.stack.imgur.com/IGOA0.png Before reaching out here for help, I s ...

What are some effective methods for selectively handling batches of 5-20k document inputs when adding them to a collection containing up to one million documents using MongoDB and Mongoose?

My MMO census and character stats tracking application receives input batches containing up to 5-20k documents per user, which need to be aggregated into the database. I have specific criteria to determine whether a document from the input already exists i ...

Troubleshooting a LESS compiling issue with my Jade layout in ExpressJS

Implementing LESS compilation on the server side using Express was successful, but I faced an issue with jade not recognizing less in layout. Error message displayed in my terminal: if(err) throw err; ^ Error: ENOENT, open '/Users/li ...

Is it possible to transmit information using the express next() function?

I am currently developing a web application that involves authentication process and session management using express. I have successfully implemented the backend sessions functionality. Now, my goal is to display on the user interface the information of t ...

Localhost subdomains are experiencing issues with HTTP cookies not functioning properly

I have successfully implemented a node/express API that creates an HTTP cookie for authentication and passes it down to my React app. This setup was based on Ben Awad's JWT HTTP Cookie tutorial on Youtube. While everything works perfectly fine when ru ...