简体   繁体   English

节点和expressjs中快速路由器方法调用和module.export方法调用和app.use()调用之间的区别

[英]Difference between express router method call and module.export method call and app.use() call in node and expressjs

i have app.js which have 我有app.js其中

var express = require('express');
var report = require('./routes/Report');

var app = express();

app.use('/api/appReport', report);

app.listen(3000);
module.exports = app;

i have Report.js 我有Report.js

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

var reportDb = require('../db/ReportDB');

reportDb.test(function(res) {
});

router.get('/all', function(req, resp) {
    reportDb.getAll(function(result) {
        resp.status(200);
        resp.send(result);
        return resp;
    });

}); 

i have ReportDB.js 我有ReportDB.js

module.exports.test = function() {
    console.log('Hello');
}

module.exports.getAll = function (callback) {
    //Some operations
};

the above code are working fine. 上面的代码工作正常。

My question is 我的问题是

when i start the node js server it is automatically calling reportDb.test() present in Report.js but it is not automatically calling router.get() present in Report.js. 当我启动节点js服务器时,它会自动调用Report.js中存在的reportDb.test(),但不会自动调用Report.js中存在的router.get()。 so i want to know what is the difference on calling of test() and router.get() ? 所以我想知道调用test()和router.get()有什么区别?

i know when we hit '/all' url then it will call router.get(). 我知道当我们点击“ / all” URL时,它将调用router.get()。 but for reportDb.test() we are not calling in app.js, so how it is automatically calling at the time of server starting ? 但是对于reportDb.test(),我们没有调用app.js,那么在服务器启动时它是如何自动调用的?

let say if i use below function inside Report.js. 假设我在Report.js中使用以下功能。 then it'll not exicute. 那就不会被激怒

function test1() {
    console.log('hello...');
}

i want to know is it app.use() calls all the method automatically which are exported ? 我想知道app.use()是自动调用导出的所有方法吗?

Its calling test() because you have written 它调用test()是因为您已经编写了

    reportDb.test(function(res) {

    });

in report.js and included reportDb.js in it. 在report.js中,并在其中包含reportDb.js。 Also you have included report.js in app.js. 另外,您还将report.js包含在app.js中。

    app.use('/api/appReport', report);

Its not that calling test() 它不是那个调用test()

Your router.get() will call when you will hit the url like localhost:3000/all 当您按localhost:3000 / all之类的网址时,您的router.get()将调用

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

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