我在node / express中读了一篇关于export / require的教程,想知道是否有人可以用我的例子向我解释: 为什么我在app.js中的路由不起作用?我需要输出什么才能使其正常工作?非常感谢!
index.js:
'use strict'
var express = require('express');
var app = express();
module.exports = app;
var PORT = process.env.PORT || 1337;
app.listen(PORT, function() {
console.log('Server is listening!');
})
app.js:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
//var app=require('./index.js');
module.exports = function() {
app.use(express.static(path.join(__dirname, '../public')));
app.use(express.static(path.join(__dirname, '../browser')));
}
答案 0 :(得分:1)
var app = express()
中声明了两个单独的快速服务器,您的示例将无法正常工作。但无论如何,如果您想使用此示例并使其正常工作,请以这种方式进行:
./ index.js
'use strict'
var express = require('express');
var setupServing = require('./setupServing.js'); //import our function
var PORT = process.env.PORT || 1337;
var app = express(); //create express app
setupServing(app); //call imported function to config our app
app.listen(PORT, function() { //start
console.log('Server is listening!');
})
./ setupServing.js
var express = require('express');
var path = require('path');
//export function which can configure static serve for app
module.exports = function(app) { //take app as an argument
app.use(express.static(path.join(__dirname, '../public')));
}
请注意,此示例仍然不够合理,我不认为您将在任何实际项目中面对此类代码,但无论如何它都可以在nodejs中运行并演示导出/需求。