Home > Blockchain >  Why am i getting an error app.get is not a function in express.js
Why am i getting an error app.get is not a function in express.js

Time:03-26

Not able to figure out why in upload.js file in the below code snippet is throwing me an error: app.get is not a function.

I have an index.js file where I have configured everything exported my app by module.exports = app and also I have app.set("upload") in it, but when I am trying to import app in upload.js file and using it, it is giving an error error: app.get is not a function.

below is the code of the index.js

const express = require("express");
const app = express();
const multer = require("multer");
const path = require("path");
const uploadRoutes = require("./src/routes/apis/upload.js");


// multer config
const storageDir = path.join(__dirname, "..", "storage");
const storageConfig = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, storageDir);
  },
  filename: (req, file, cb) => {
    cb(null, Date.now()   path.extname(file.originalname));
  },
});
const upload = multer({ storage: storageConfig }); // local upload.

//set multer config
app.set("root", __dirname);
app.set("storageDir", storageDir);
app.set("upload", upload);

app.use("/api/upload", uploadRoutes);

const PORT = process.env.PORT || 5002;

if (process.env.NODE_ENV === "development") {
  app.listen(PORT, () => {
    console.log(`Server running in ${process.env.NODE_ENV} on port ${PORT}`);
  });
} else {
  module.exports.handler = serverless(app);
}
module.exports = app;

upload.js file

const express = require("express");
const router = express.Router();
const app = require("../../../index");

const uploadDir = app.get("storageDir");
const upload = app.get("upload");

router.post(
  "/upload-new-file",
  upload.array("photos"),
  (req, res, next) => {
    const files = req.files;

    return res.status(200).json({
      files,
    });
  }
);

module.exports = router;

CodePudding user response:

The problem is that you have a circular dependency.

App requires upload, upload requires app.

Try to pass app as a parameter and restructure upload.js to look like:

const upload = (app) => {
   // do things with app
}

module.exports = upload

Then import it in app and pass the reference there (avoid importing app in upload).

import upload from './path/to/upload'
const app = express();
// ...
upload(app)
  • Related