我无法弄清楚为什么下面代码片段中的upload.js文件会抛出一个错误:app.get不是一个函数。
我有一个index.js文件,我已经配置了所有内容,并通过module.exports = app导出我的应用程序,我还在其中使用了app.set("upload"),但是当我试图在upload.js文件中导入app并使用它时,它会出现错误:error: app.get不是一个函数。
以下是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;