【问题标题】:nodejs express reuse a route get method in another filenodejs express 在另一个文件中重用路由获取方法
【发布时间】:2018-07-22 18:26:49
【问题描述】:

在文件 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 从用户文件中的文件组获取路由?

【问题讨论】:

  • 提取通用功能并创建通用实用函数,在需要时导入并在两个路由中调用?
  • @Li357 我如何导出它,因为我已经在导出路由器并且它正在应用程序中使用...如何不影响当前设置?
  • 什么意思?使用通用功能创建一个新文件。然后将该文件导入users.jsgroups.js 并使用该函数。

标签: javascript node.js express


【解决方案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 中导入该实用程序,然后您可以访问不同模块中的相同状态变量。

【讨论】:

    【解决方案2】:

    试试这个,使用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);
            });
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多