简体   繁体   English

需要中间件功能的路由

[英]Route requiring a middleware function

I'm creating my routes module in nodejs with socket.io 我正在使用socket.io在nodejs中创建我的路由模块

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. 因此,假设您在加载此模块的调用router.use()执行app.use()router.use() ,则不会从函数中返回路由器,因此无法挂接到该路由器,并且会收到错误消息看到。

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. 然后函数将返回router.use()将满意的路由器。 You can pass either middleware or a router to .use() . 您可以将中间件或路由器传递给.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. 调用该函数时,它将返回undefined的等效项。 Also, normally a route is defined before the endpoint. 同样,通常在端点之前定义一条路由。 It's typically structured like: 它的结构通常如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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