范围在快速路线中有点奇怪

时间:2017-11-21 15:11:53

标签: node.js express router

我遇到了以下问题:快速路由器中的options变量没有使用正确的options变量。有什么建议吗?

router.use('/test1', new Factory("test1") );
router.use('/test2', new Factory("test2") );

function Factory(options) {
    router.use((req,res,next) => {
        res.json(options)
    })
    return router
};

/*
Returns :
/test1 "test1"
/test2 "test1" ???
*/

3 个答案:

答案 0 :(得分:0)



function Factory(options) {

    return (req,res,next) => {
        res.json(options)
    })
};

router.use('/test1', new Factory("test1") );
router.use('/test2', new Factory("test2") );




答案 1 :(得分:0)

TL;博士;

请改用它。

router.get("/:options", Factory);

function Factory(req, res, next){
    const options = req.params.options;
    res.json(options);
}

为什么你的东西不能按预期工作

在你的工厂里你这样做:

router.use((req, res, next) => {
    res.json(options);
});

这句话告诉express:嘿,每当有请求进来时,运行这个中间件:

(req, res, next) => {
        res.json(options);
    })

请注意,您没有为此指定路线,它只是采用app.use(handler)格式,因此它将针对每个请求运行。

以上你这样做:

router.get("/test1", new Factory("test30"));

现在当快递看到它说,哦,这里是/test1的处理程序,让我将该处理程序注册到该路由。当它注册处理程序时,它会遇到这个表达式:new Factory("test1")。请注意,这是一个表达式,将在路由注册时执行而在处理请求时不执行。它基本上可以这样重写:router.get("/test1", Factory("test30")),结果是:

router.get("/test1", router.use((req, res, next) => {
    res.json("test1");
    return router;
}));

这部分:

router.get("/test1", )

取决于这部分:

router.use((req, res, next) => {
        res.json("test1");
        return router;
    })

这意味着后者将首先执行。这意味着在最后,您的所有代码实际上都是这样的:

const resultOfThisLine = 
router.use((req, res, next) => {
    res.json("test1"); //You passed test1 as options to the factory
    return router;
});

router.get("/test1", resultOfThisLine);

router.get("/test2", router.use((req, res, next) => {
    res.json("test1"); //You passed test1 as options to he factory
    return router;
}));

如您所见,

   router.use((req, res, next) => {
        res.json("test1"); //You passed test1 as options to the factory
        return router;
    });

实际上是在其他所有内容之前注册的,因为它返回一个响应,所以不会有任何其他内容被调用。此外,此处理程序将响应任何请求,因为没有附加特定的URL。

答案 2 :(得分:0)

感谢您的快速反应。它让我意识到我需要创建一个新的路由器对象。

像这样:

const express = require('express')
const router = express.Router();

router.use('/test1', new Factory("test1"));
router.use('/test2', new Factory("test2"));

function Factory(options) {
    const router2 = express.Router();

    router2.get("", handleRoute.bind({ options: options }))
    router2.post("", handleRoute.bind({ options: options }))

    function handleRoute(req, res, next) {
        res.json({ message: "hello", options: options })
    }

    return router2
};