简体   繁体   English

node.js(express框架):要求和发布

[英]node.js (express framework): require and post

app.js: app.js:

var app = express();

require('./other_file.js')(app);

other_file.js: other_file.js:

app.post('/test', function(req, res) {
    console.log(true);
});

result: app is not defined. 结果:应用程序未定义。

How to use express methods in require file? 如何在require文件中使用Express方法?

Thanks in advance. 提前致谢。

other_file.js should be something like that: other_file.js应该是这样的:

 module.exports = function(app) {
   app.post('/test', function(req, res) {
      console.log(true);
   });
 }

Longer story: when you require() a file you get back an object (the exports object). 更长的故事:当require()一个文件时,您将获得一个对象( exports对象)。 If you want to get back a function you need to make your function replace the exports object. 如果要取回函数,则需要使函数替换导出对象。 To achieve that you need to assign your function to module.exports 为此,您需要将功能分配给module.exports

You have to specifically export the member you want to expose with a require. 您必须专门导出要与需求公开的成员。

other_file.js should look like this other_file.js应该看起来像这样

module.exports = function(app) {
  app.post('/test', function(req, res) {
    console.log(true);
  });
}

where module.exports is the member that is returned when the file is used with a require() statement. 其中module.exports是当文件与require()语句一起使用时返回的成员。

Node itself borrows from the CommonJS module spec . 节点本身借鉴了CommonJS模块规范

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

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