为什么我收到错误 app.get is not a function in express.js

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

无法弄清楚为什么下面代码片段中的 upload.js 文件向我抛出一个 错误:app.get 不是一个函数。

我有一个 index.js 文件,我在其中配置了通过 module.exports = app 导出我的应用程序的所有内容我也有 app.set("upload") ,但是当我试图 import app in upload.js 文件并使用它,它给出了一个错误 error: app.get is not a function.

下面是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 文件

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;

问题是你有一个循环依赖。

应用需要上传,上传需要应用。

尝试将应用程序作为参数传递并重组 upload.js 使其看起来像:

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

module.exports = upload

然后将其导入应用程序并在那里传递引用(避免在上传时导入应用程序)。

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