app.get 不是 express.js 中的函数

app.get is not a function in express.js

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

//这是我的app.js文件

const express = require('express');
const app = express();
const helpers = require('./helpers');
const routes = require('./index')

app.use((req, res, next) => {
    app.locals.h = helpers;
    next();
});

app.use('/', routes);

app.set('views',(__dirname));
app.set('view engine', 'pug');

app.listen(3000,()=>console.log('port 3000'));

module.exports = app;

//这是我的index.js文件

const app = require('./app')

app.get('/',(req,res) => {
   res.render('template');
})

module.exports = router;

//helpers.js

exports.title = "NODEjs";

//template.pug

doctype html
html
  head
    title=`${h.title}`
  body
    h1 myHeading #{h.title}

你有一个循环依赖循环而不是创建一个无限循环,require() 子系统检测到它并且无法加载你的模块。

app.js 中,您加载 index.js。在 index.js 中,您加载 app.js。循环依赖循环。

有两种不同的技术可用于解决您的特定问题。您似乎正在使用一种技术和另一种技术,这就造成了您的问题。

在单独的文件中定义新路由的经典方法是让该文件创建并导出自己的路由器。然后它将路由分配给路由器(而不是 app),因此其他文件根本不需要 app 对象。因为你展示了 module.exports = router,所以你似乎掌握了该技术的一部分,但只是其中的一部分。

代码如下:

// app.js
const express = require('express');
const app = express();
const helpers = require('./helpers');

app.use((req, res, next) => {
    app.locals.h = helpers;
    next();
});

// hook in routes from the index.js router
app.use('/', require('./index'));

app.set('views',(__dirname));
app.set('view engine', 'pug');

app.listen(3000,()=>console.log('port 3000'));


// index.js
const router = require('express').Router();
router.get('/',(req,res) => {
    res.render('template');
});

module.exports = router;

您还可以在加载时将 app 传递给 index.js,而不是让它尝试导入 app。这也解决了循环依赖问题。

const express = require('express');
const app = express();
const helpers = require('./helpers');

// pass app here so it can register routes
require('./index')(app);

app.use((req, res, next) => {
    app.locals.h = helpers;
    next();
});

app.use('/', routes);

app.set('views',(__dirname));
app.set('view engine', 'pug');

app.listen(3000,()=>console.log('port 3000'));

更改 index.js 以导出您调用的模块构造函数并将 app 传递给:

module.exports = function(app) {
    app.get('/',(req,res) => {
        res.render('template');
    })
}

在第一行添加括号:

const express = require('express')();

应该接受第一个答案。 这只是由于在这种情况下的循环依赖性而发生的。