Search code examples
javascriptnode.jsexpressexpress-router

Router.use() requires a middle function, but got an Object. module.exports = router exists on page


from app.js

 // REQUIRE ROUTES
    var commentRoutes = require("./routes/comments"),
    bpostRoutes = require("./routes/bposts"),
    indexRoutes = require("./routes/index");


   //USE ROUTES
   app.use("/", indexRoutes);
   app.use("/bposts", bpostRoutes);
   app.use("/bposts/:id/comments", commentRoutes);

from routes/index.js

     var express = require("express");
     var router  = express.Router();

     //LANDING -root route
     router.get("/", function(req, res){
     res.render("landing"); 
   });

   module.exports = router;

I am currently trying to setup all my routes before I create a DB or do anything meaningful for the blog. When I encountered this problem the first time it was because I didn't use

module.exports = router;

on each route page I had. Express router is installed and saved to package.json. Each time I have run into this error it's a quick fix because I didn't include export statement. Now I have finally remembered to add it in and I am still receiving this error message. Any suggestions or advice would be greatly appreciated!

 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 (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:458:13)
    at EventEmitter.<anonymous> (/home/ubuntu/workspace/node_modules/express/lib/application.js:220:21)
    at Array.forEach (native)
    at EventEmitter.use (/home/ubuntu/workspace/node_modules/express/lib/application.js:217:7)
    at Object.<anonymous> (/home/ubuntu/workspace/app.js:25:5)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3

Solution

  • I use an IDE callled C9(Cloud 9) and only use the free service, which means lower performance and potential downtime prioritizing user space for paid cx. So I logged out of my account and relogged in. It then cleared and cleaned up the workspace as it was launching my app. After this I was able to preview my app without any issue. Time to upgrade! I changed nothing in the code, no additions or subtractions. It's the first time I have seen it happen in 6 months I have used it. This did resolve the issue. Thanks for all the help and suggestions!