代码之家  ›  专栏  ›  技术社区  ›  Shaggie

在app.js中通过foreach添加路由时出现Router.use()抛出错误

  •  0
  • Shaggie  · 技术社区  · 7 年前

    当我使用相同的方法时,我陷入了一个在我以前的项目中不是问题的问题。我正在尝试以下方式添加路由和文件路径:

    app.use(app.router);
    
    APIRoutes.forEach(function (object) {
        app.use(object.route, require(object.path));
    });
    

    一旦我这样做,它就会显示错误

    [nodemon] restarting due to changes...
    [nodemon] starting `node ./bin/www`
    [nodemon] restarting due to changes...
    [nodemon] starting `node ./bin/www`
    c:\Node\mytestapp\node_modules\express\lib\router\index.js:458
      throw new TypeError('Router.use() requires a middleware function but got a 
    ' + gettype(fn))
      ^
    
    TypeError: Router.use() requires a middleware function but got a Object
    at Function.use 
    (c:\Node\mytestapp\node_modules\express\lib\router\index.js:458:13)
    at Function.<anonymous> 
    (c:\Node\mytestapp\node_modules\express\lib\application.js:220:21)
    at Array.forEach (<anonymous>)
    at Function.use 
    (c:\Node\mytestapp\node_modules\express\lib\application.js:217:7)
    at c:\Node\mytestapp\app.js:34:8
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (c:\Node\mytestapp\app.js:33:11)
    

    我在以前的项目中也做了同样的工作,他们的工作很好。对于这个问题,我得到的更多见解是,我以前的项目是在express 2.0.0框架中进行的,现在一些组件被删除了。但我没有找到解决办法。

    product.js文件

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    var ProductModel = new Schema({
    productId: Number,
    name: String,
    quantity: Number,
    price: Number,
    activeStatus: Number
    });
    
    const Product = mongoose.model('myProduct', ProductModel);
    module.exports = Product;
    
    0 回复  |  直到 7 年前
    推荐文章