node.js (express framework): require and post
node.js (express framework): require and post
app.js:
var app = express();
require('./other_file.js')(app);
other_file.js:
app.post('/test', function(req, res) {
console.log(true);
});
结果:未定义应用程序。
如何在require文件中使用express方法?
提前谢谢。
other_file.js
应该是这样的:
module.exports = function(app) {
app.post('/test', function(req, res) {
console.log(true);
});
}
长话短说:当您require()
一个文件时,您会返回一个对象(exports
对象)。如果你想取回一个函数,你需要让你的函数替换exports对象。要实现这一点,您需要将您的功能分配给module.exports
您必须特别导出您想要用require公开的成员。
other_file.js
应该像这个
module.exports = function(app) {
app.post('/test', function(req, res) {
console.log(true);
});
}
其中module.exports
是当文件与require()
语句一起使用时返回的成员。
Node本身借用了CommonJS模块规范。
相关文章:
- Selenium WebDriver and JavaScript change
- 当使用extern和目标JavaScript时,我如何强制Haxe编译器使用require语句
- 在gump和nodejs中使用Typescript时,未定义对require和exports的引用
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- Typescript导入导出的类会发出require(..),从而导致浏览器错误
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Dojo require() and AMD (1.7)
- meteor.js and npm require fs
- Require.js and Parsley.js
- WebPack and Require
- Backbone.js and Require.js tool r.js
- Backbone.js + Require.js and ViewsFactory
- require() in Browserify and Gulp
- node.js (express framework): require and post