404 error when uploading image (express, mongodb, multer)

exports.postAddProduct = (req, res, next) => {
  const title = req.body.title;
  const image = req.file
  const price = req.body.price;
  const description = req.body.description;
  if (!image) {
    return res.status(422).render('admin/edit-product', {
      pageTitle: 'Add Product',
      path: '/admin/add-product',
      editing: false,
      hasError: true,
      product: {
        title: title,
        price: price,
        description: description
      },
      errorMessage: 'Attached file is not an image.',
      validationErrors: []
    });
  }
  const errors = validationResult(req);

  if (!errors.isEmpty()) {
    console.log(errors.array());
    return res.status(422).render('admin/edit-product', {
      pageTitle: 'Add Product',
      path: '/admin/add-product',
      editing: false,
      hasError: true,
      product: {
        title: title,
        imageUrl: imageUrl,
        price: price,
        description: description
      },
      errorMessage: errors.array()[0].msg,
      validationErrors: errors.array()
    });
  }

  const imageUrl = image.path;
  

  const product = new Product({
    // _id: new mongoose.Types.ObjectId('5badf72403fd8b5be0366e81'),
    title: title,
    price: price,
    description: description,
    imageUrl: imageUrl,
    userId: req.user
  });
  product
    .save()
    .then(result => {
      // console.log(result);
      console.log('Created Product');
      res.redirect('/admin/products');
    })
    .catch(err => {
      // return res.status(500).render('admin/edit-product', {
      //   pageTitle: 'Add Product',
      //   path: '/admin/add-product',
      //   editing: false,
      //   hasError: true,
      //   product: {
      //     title: title,
      //     imageUrl: imageUrl,
      //     price: price,
      //     description: description
      //   },
      //   errorMessage: 'Database operation failed, please try again.',
      //   validationErrors: []
      // });
      // res.redirect('/500');
      const error = new Error(err);
      error.httpStatusCode = 500;
      console.log(imageUrl)
      return next(error);
    });
};`

also, app.js code:

const multer = require('multer')
const fileStorage = multer.diskStorage({
    destination: (req,file, cb)=>{
        cb(null, 'images' )
    },

    //first argument of cb - error
    filename: (req,file,cb)=>{
        cb(null, new Date().toISOString()+ '-'+ file.originalname)
    }
})
const fileFilter = (req,file,cb)=>{
    if(file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype=== 'image/jpeg'){

        cb(null, true)
    }
    cb(null, false)
}

app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const authRoutes = require('./routes/auth');
const shopRoutes = require('./routes/shop');



const errorController = require('./controllers/error');

const User = require('./models/user')

app.use(bodyParser.urlencoded({extended: false}));
app.use(multer({storage: fileStorage, fileFilter: fileFilter }).single('image'))


I have a function, which sends product data to mongodb. It worked well when I had just image url instead of file upload. However, after incorporating file upload logic, it encountered issues, leading to redirection to a 500 error page. I’m seeking guidance on resolving this matter and ensuring the smooth integration of file uploads, preserving the functionality of the function while preventing redirection errors to the error page. How can I rectify this situation and maintain the desired functionality?

  • As we keep saying here all the time – the very first thing you need to do, when you get a 500 Internal Server error, is go and check what the error log has to say about that.

    – 

  • after loging error it throws: Failed to load resource: the server responded with a status of 404 (Not Found). but redirect is on 500 page)

    – 




  • “Failed to load resource: the server responded with a status of 404 (Not Found)” – that is a client-side error message. “but redirect is on 500 page” – what “redirect”? If you got a 404 response, you can hardly have gotten a redirect response at the same time. And we still don’t know what the error log on the server side has to say.

    – 

  • I dont get any error on server side. tried to log everywhere. third day stucked on this process…

    – 

  • If you got an actual 500, then you should find some info about this in the log files (unless you had that explicitly disabled.) But maybe you are not actually getting one … I already asked you to please clarify, what “redirect is on 500 page” actually means.

    – 

Leave a Comment