简体   繁体   中英

Route requiring a middleware function

I'm creating my routes module in nodejs with socket.io

var express = require("express"); // call express
var taskSchema = require("../models/taskModel");
var mongoose = require("mongoose");
var router = express.Router(); // get an instance of the express Router
module.exports = function (io) {
    router.use(function (req, res, next) {
        io.sockets.emit('payload');
        console.log("Something is happening.");
        next(); 
    });
    router
        .route("/tasks")
        .post(function (req, res, next) {
            ...
        });
    router
        .route("/tasks")
        .get(function (req, res) {
            ...
        });
};

When I compile server I get this error

TypeError: Router.use() requires a middleware function but got a undefined

It appears to me that the problem is probably in the code that loads this module because you never export the actual router. So, assuming you do app.use() or router.use() in the caller who loads this module, your aren't returning the router from your function so there's no way to hook that router in and you would get the error you see.

I'm guessing that you can fix this by just returning the router from your exported function:

var express = require("express"); // call express
var taskSchema = require("../models/taskModel");
var mongoose = require("mongoose");
var router = express.Router(); // get an instance of the express Router
module.exports = function (io) {
    router.use(function (req, res, next) {
        io.sockets.emit('payload');
        console.log("Something is happening.");
        next(); 
    });
    router
        .route("/tasks")
        .post(function (req, res, next) {
            ...
        });
    router
        .route("/tasks")
        .get(function (req, res) {
            ...
        });
    return router;            // <===========  Add this
};

Then, when you do:

let m = require('yourModule');
router.use(m(io));

Then function will return the router that router.use() will be happy with. You can pass either middleware or a router to .use() .


If this guess isn't quite on target, then please show us the code that loads and calls this module.

When that function is called it's gonna return the equivalent of undefined. Also, normally a route is defined before the endpoint. It's typically structured like:

 let myRouter = new Router(); Router.use('something', middlewareFunction, someotherprocess); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM