gpt4 book ai didi

javascript - 如何将应用程序实例传递给 ExpressJs 中的路由文件?

转载 作者:行者123 更新时间:2023-12-02 21:05:54 25 4
gpt4 key购买 nike

我正在使用 Express 框架来开发后端 API,但今天遇到一个问题。我有一个 server.js (条目)文件,我想将 app 实例传递给 routes/api.js 文件。我想检查端点前缀是否为 /api/v2 然后我想调用 routes/index.js 文件。但我无法实现这种方法。我在下面添加 server.js routes/api.jsroutes/index.js 文件的代码。

Server.js

/** Core Packages */

/** NPM Packages */
const express = require('express');

/** Custom Packages */
const routerApi = require('./routes/api');
const dbConnect = require('./config/database');

const app = express();
dbConnect();

app.use(express.json());
app.use(express.urlencoded({extended: true}));

routerApi(app);

const PORT = 4000;

/** Creating a Server */
const server = app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});

routes/api.js

/** Core Packages */

/** NPM Packages */

/** Custom Packages */

const apiRouter = (app) => {
app.use('/api/v2', require('./index')(app));
};

module.exports = apiRouter;

routes/index.js

/** Core Packages */

/** NPM Packages */

/** Custom Packages */

const routes = (app) => {
app.all('/*', (req, res, next) => {
if (req.path === '/')
return res.status(200).send({msg: 'Welcome to landing page.'});
}
}

module.exports = routes;

错误

TypeError: Router.use() requires a middleware function but got a undefined
at Function.use (/home/admini/Documents/skreem-api-node/node_modules/express/lib/router/index.js:458:13)
at Function.<anonymous> (/home/admini/Documents/skreem-api-node/node_modules/express/lib/application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (/home/admini/Documents/skreem-api-node/node_modules/express/lib/application.js:217:7)
at apiRouter (/home/admini/Documents/skreem-api-node/routes/api.js:9:7)
at Object.<anonymous> (/home/admini/Documents/skreem-api-node/server.js:52:1)
at Module._compile (internal/modules/cjs/loader.js:816:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
at internal/main/run_main_module.js:21:11

谁能帮我解决这个问题吗?我们将提供任何形式的帮助。谢谢你!

最佳答案

server.js 文件中,在文件底部添加以下内容:

module.exports = app;

然后在需要的文件中 require server.js :

const app = require('path to server.js file');

关于javascript - 如何将应用程序实例传递给 ExpressJs 中的路由文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61228920/

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