[英]nodejs express reuse a route get method in another file
在文件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
文件从用户文件中的文件组获取路由?
尝试此操作,使用npm request module
命中自己的路由/ api:通过npm install request --save
命令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);
});
}
您只需将其放入外部模块中,然后使用require将其导入:
ROUTE1:
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中,然后可以访问不同模块中的相同状态变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.