Issue: Encountered an error when attempting to use the multer module

Hello experts, I am venturing into backend technology for the first time. As part of my project, I am trying to upload files and text to my database using nodejs and mongoDB. However, I keep encountering an error message that is impeding my progress. I would greatly appreciate any advice or guidance on this matter. Thank you in advance.

Here is a snippet of my server code:

const express = require('express');
const {default:mongoose} = require('mongoose');
const multer = require('multer');
const Storage = multer.diskStorage({
    destination: 'uploads',
    filename:(req, file, cb)=> {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, file.originalname);
    },
})    
const upload = multer({
    storage:Storage
}).single('image')
const Blog = require('./models/blog.js');
    
mongoose
    .connect("mongodb://127.0.0.1:27017/filesUpload") 
    .then(()=>{console.log('Mongo server has started')})
    .catch(()=>{console.log('Connection to Mongo Failed')})

const app = express();
const port = 3000;
app.set('views engine', 'ejs')
app.use(express.static("public"));
app.use(express.urlencoded());
app.use(express.json());

app.get("/", async (req, res)=>{
    const blogs = await Blog.find()
    res.render('index.ejs', {title: 'HOME', blogs})    
})

app.post("/blogs/create", (req, res)=>{    
    upload = (req, res, (err)=>{
        if (err){
            console.log(err)
        }
        else{    
            const blog = new Blog({
                title: req.body.title,
                snippet: req.body.snippet,
                body: req.body.body,
                image: {
                    date: req.file.filename,
                    contentType: "image/jpg"
                }
            });    
            blog.save().then(()=>{
                res.redirect('/')
            }).catch((err)=>{
                console.log(err)
            }) 
        }
    })
})    

app.listen(port, ()=>{
    console.log('Server is currently running')
})

When I attempt to initiate a post request, I encounter the following error message:

TypeError: Assignment to constant variable.
    at C:\Users\go\Desktop\not\files\app.js:53:12
    at Layer.handle [as handle_request] (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\go\Desktop\not\files\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\index.js:280:10)
    at jsonParser (C:\Users\go\Desktop\not\files\node_modules\body-parser\lib\types\json.js:119:7)
    at Layer.handle [as handle_request] (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\layer.js:95:5)

Answer №1

It appears that certain errors in your code are causing the problem at hand. Below is a revised version of your code with the necessary corrections:

const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const path = require('path'); // Addition for handling paths
const Storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads'); // Rectified destination path
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname)); // Extension appended correctly
  },
});
const upload = multer({
  storage: Storage,
}).single('image');
const Blog = require('./models/blog.js');

mongoose
  .connect('mongodb://127.0.0.1:27017/filesUpload', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log('Mongo server has started');
  })
  .catch(() => {
    console.log('Connection to Mongo Failed');
  });

const app = express();
const port = 3000;

app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true })); // Include { extended: true }
app.use(express.json());

app.get('/', async (req, res) => {
  const blogs = await Blog.find();
  res.render('index.ejs', { title: 'HOME', blogs });
});

app.post('/blogs/create', (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      console.log(err);
    } else {
      const blog = new Blog({
        title: req.body.title,
        snippet: req.body.snippet,
        body: req.body.body,
        image: {
          date: req.file.filename,
          contentType: 'image/jpg',
        },
      });
      blog
        .save()
        .then(() => {
          res.redirect('/');
        })
        .catch((err) => {
          console.log(err);
        });
    }
  });
});

app.listen(port, () => {
  console.log('Server is currently running');
});

Modifications and rectifications applied to the code:

  1. Included the path module for appropriate handling of file extensions.
  2. Rectified the destination path configuration within the Storage section.
  3. Corrected app.set('views engine', 'ejs') to app.set('view engine', 'ejs').
  4. Added { extended: true } in the express.urlencoded() middleware.
  5. Adjusted the reassignment of the upload variable to upload(req, res, ...) for proper invocation of the middleware.

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

Coming back from retrieving data from an API

I'm having trouble with a function that performs a POST request to retrieve access tokens from an API. Although the function successfully prints the token to the console, I haven't been able to figure out how to properly parse and save the access ...

Encountering an issue during the installation of Express using the Windows command prompt

I have successfully installed Node.js in the C:\Program Files directory. Both Node.js and npm are working fine as I checked their versions. Below is the description and version information of the software/hardware I am using: OS:- Windows 7 Enterpri ...

Socket.io continuously refreshing and updating multiple instances

Incorporating socket.io into a small React application, I configured all the listeners within the "componentWillMount" method. See the code snippet below for reference: componentWillMount() { const socket = io(); socket.on('update', f ...

What methods can be used to report errors with Sentry while offline?

One key feature of my app is its ability to function both offline and online. However, I'm wondering how I can ensure that errors are still sent to my Sentry dashboard even when a user is offline. ...

encountering difficulties while installing node-sass using npm

As I work on creating a local environment for PrestaShop, I am facing an issue during the npm installation process. There seems to be an error occurring when trying to install node-sass. Can someone provide guidance on resolving this issue? ...

Issue occurred when trying to read properties that are undefined, specifically in the 'toLowerCase' function. Additionally, an array named keys has been declared with the values "type"

An error occurs when trying to read properties of undefined, specifically 'toLowerCase' const fields = ["model", "brand"] const filterResults = () => { return availableCars.filter((car) => fields.some((field) => c ...

Nodemon causing server to fail to start or connect

I recently set up a new project using Express, Node, and Nodemon. I configured the basic files to ensure it starts properly, but when I run npm start in the terminal, it seems to initiate without any errors being displayed regarding the server's locat ...

Can you help me identify the issue with my current Jade for loop implementation?

Here is my full loop code written in Jade: block content div(class='row') div(class='col-lg-12') h1(class='subject') 로또라이 div(class='row') div(class='col-lg-8') - for (var ...

Can you provide steps for running "npm run watch" on a particular address and port in Laravel Mix?

Is there a way to run npm watch with a specific URL and port? In the package.json file, I have the following line: "watch": "mix watch", In the scripts section, this works fine with the command npm run watch and is accessed via localh ...

Tips for sending functions from client to server in Node.js

I'm working with this code snippet: const http = require('http'); const fs = require('fs'); const handleRequest = (request, response) => { response.writeHead(200, { 'Content-Type': 'text/html' ...

Facilitating the integration of both Typescript and JavaScript within a Node application

We are currently integrating Typescript into an existing node project written in JS to facilitate ongoing refactoring efforts. To enable Typescript, I have included a tsConfig with the following configuration: { "compilerOptions": { "target": "es6", ...

I'm not sure how I can retrieve the pollId from a ReactJS poll

In my React code, I am fetching a poll using an API. However, I am facing an issue while working on the handleChange function for making a POST API request. The information required for the request includes PollId, userId, and answer. I am able to retrieve ...

How can I display a timestamp when logging using the npm debug package in a node.js environment?

I am currently utilizing the npm debug package to output messages to the console (instead of using the regular console.log()). Is there a method to include a timestamp for each message using this debug library? For instance, I would like all log messages t ...

EJS files do not show variables passed from Node

I am currently developing a 'preferences' section on my website, where users can make changes to their email addresses and passwords. Within this preferences page, I aim to showcase the user's current email address. router.get("/settings", ...

Issue with authentication persistence between React frontend and Node.js backend causing passport not to persist user credentials

I have implemented a Node.js and express backend along with a React frontend. Currently, I am using Passport.js with the Local Authentication Strategy. The issue arises when I log in on my React login component; it works perfectly in the Node.js app.post(" ...

Error in TypeORM - violation of unique constraint due to duplicate key (deferrable foreign key)

My current scenario involves the following: export default class BucketEntity extends Entity { @Column({ type: "enum", enum: BucketType, default: BucketType.Notes, }) type: BucketType; @Column() title: string; @OneToOne( ...

Leverage a configuration variable from package.json in npm commands

Can a variable from the config section be reused? ... "config": { "source": "Hello", "root": "$npm_package_config_source World" } ... I have been able to reuse variables in the scripts section, but I am unsure if it is possible in the config sectio ...

Issues with npm, node-gyp, and gulp encountered while using MAC OS X Yosemite version 10.10.5

Struggling to install npm, node-gyp, and gulp on my MAC for a Laravel project. Despite researching extensively online, I haven't found a solution that works for me yet, indicating potential issues with the paths. I have attempted: Installing node/n ...

Issue encountered while generating a fresh migration in TypeORM with NestJs utilizing Typescript

I am currently working on a Node application using TypeScript and I am attempting to create a new migration following the instructions provided by TypeORM. Initially, I installed the CLI, configured my connection options as outlined here. However, when I ...

Why does socket.io have trouble connecting when clients are using different IP addresses on separate wifi networks?

I've encountered an issue where socket.io won't connect when clients are on different wifi networks (ip address) using my self-configured Ubuntu Nginx server. Strangely enough, it works perfectly fine on a pre-configured Heroku server. Here is a ...