nodejs在另一个文件中重用路由获取方法

时间:2018-07-22 18:26:49

标签: javascript node.js express

在groups.js文件中,我具有以下路线:

router.get('/status', function(req, res, next) {
    // some data
    return res.status(200).json(someData);
}
module.exports = router;

在文件users.js中,我具有以下路线:

router.get('/create', function(req, res, next) {

    // re-use the groups route '/status' here and get 'someData'
    // do some stuff with 'someData'
    // do more bunch of data

    return res.status(200).json(bunchOfData);
}

如何使用status从用户文件中的文件组获取路由?

2 个答案:

答案 0 :(得分:1)

尝试一下,使用npm request module来打自己的路线/ api: 通过npm install request --save命令安装

要求它: const request = require('request');

router.get('/create', function(req, res, next) {

        // re-use the groups route '/status' here and get 'someData'
        // do some stuff with 'someData'
        // do more bunch of data

        //for local use: http://localhost:<port of server>/status?<query string>            
        request('http://<host>:<port>/status?<query string>', function (error, response, body) {

            console.log('error:', error); // Print the error if one occurred
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            console.log('body:', body); // Print the HTML for the Google homepage.

             return res.status(200).json(body);
        });
    }

答案 1 :(得分:1)

您只需将其放入外部模块中,然后使用require将其导入:

路线1:

router.get('/status', function(req, res, next) {
    // some data
    return res.status(200).json(someData);
}
module.exports = router;

路线2:

router.get('/create', function(req, res, next) {

    // re-use the groups route '/status' here and get 'someData'
    // do some stuff with 'someData'
    // do more bunch of data

    return res.status(200).json(bunchOfData);
}

Utility.js

let status;
// status = whatever you need it to be
module.exports = status;

现在将实用程序同时导入route1和route2,然后可以在不同模块中访问相同的状态变量。