gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:32:51 25 4
gpt4 key购买 nike

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

我有一个 index.js 文件,我在其中配置了通过 module.exports = app 导出我的应用程序的所有内容,而且我还有 app.set("upload") ,但是当我尝试在 upload.js 文件中导入应用并使用它时,它给出了一个错误错误: 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;

上传.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;

最佳答案

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

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

尝试将 app 作为参数传递并重组 upload.js 如下所示:

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

module.exports = upload

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

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

关于javascript - 为什么我收到错误 app.get is not a function in express.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71583858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com