Home > Software engineering >  Why doesn't work the multer as a middleware?
Why doesn't work the multer as a middleware?

Time:07-09

I the app.js there is a direct route app.post('/upload', upload.single('image'), (req, res) => { res.json({ message: 'pic uploaded' }); });

When I make a post request to /upload, the image will be uploaded. However, when I use it like app.use('/phones', phoneRoutes); then the image won't be uploaded. Can you tell me where is the mistake? In both files everything is the same, but as I said, it works only in the 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;

CodePudding user response:

Your statement

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

contains a relative path, which is probably evaluated relative to the current working directory of the Node.js process. It is safer to make it relative to the directory containing the Javascript file phoneRoutes.js:

cb(null, __dirname   '/../images');
  • Related