我正在将我的项目切换到ES6,并将所有内联require
替换为import
。替换顶层的require
没有问题,但是当我尝试替换内联的require
时,我得到了TypeError: app.use() requires a middleware function
// We need these modules to be present.
import path from "path";
import dotEnv from "dotenv";
import express from "express";
import { fileURLToPath } from 'url';
import connectToDatabase from "./database.js";
import morganMiddleware from "./middlewares/morgan.middleware.js";
// Initialise exress
const app = express();
// Initialise dotEnv;
dotEnv.config();
// Define file and directory path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Load environment variables
const PORT = process.env.PORT || 1313;
// Properly parse the json and urlencoed data
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// Add the morgan middleware
app.use(morganMiddleware);
// When we respond with a json object, indent every block with 4 spaces.
app.set("json spaces", 4);
// Where should we look for the static files
app.use(express.static(path.join(__dirname, "../public")));
//Load the different routes
app.use(import("./controllers/index.js"));
// Connect to database
connectToDatabase();
// Custom Error handling
app.use((req, res) => {
res.status(404).json({
type: "error",
message: "404: Page not Found"});
});
app.use((error, req, res, next) => {
res.status(500).json({
type: "error",
message: "500: Internal Server Error"});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
字符串
有人知道这是怎么回事吗?
这是controllers/index.js
文件中的内容
// Loading the modules
import { Router } from "express";
const router = Router()
// Load the models
import ProjectsData, { addProject } from "../models/projects.js";
router.post("/", (req, res) => {
res.send("Cool. We are working. Now you can proceed to cry.");
});
export default router;
型
1条答案
按热度按时间wpx232ag1#
在我看来,把导入移到其他的地方,因为你每次都要导入它。
第一个月
app.use(indexController)
个但是如果你真的需要内联导入一些东西,这里有documentation。但我会给予你一个例子。
所有内联导入都返回promise并且需要等待。此外,当您只编写
import('...')
时,它需要一个默认导出,而您在该特定文件中没有这个导出。所以这就是你解决问题的方法。app.use((await import("./controllers/index.js")).default)
个