Node.js投掷不能GET /与快递

我开始学习node.js,我正在使用express。

我的项目结构是:

---CardDemo -----view -------index.html -----server -------controller ---------indexController.js -------app.js 

现在代码:

indexController.js:

 var mongoose = require('mongoose'); var app = require('../server/app'); app.get('/', function(req, resp){ resp.sendFile('../view/index.html'); }); 

app.js:

 var express = require('express'); var app = express(); var port = 8000; app.listen(port, function(error, response){ if (error){ console.log("Failed to run server!"); } }); module.exports = app; 

当我在做localhost:8000/我得到:

 Cannot GET / 

出了什么问题?

你在做什么错了是如何和你作为一个启动文件运行。

尝试运行(对于现有文件,源代码和文件夹结构):

node server/controller/indexController.js (因为你是导出应用程序而不是indexController)

然后尝试http:// localhost:8000 /


推荐的

项目结构:

 |-- CardDemo | |-- controllers | | `-- userController.js | |-- models | | `-- userSchemaModel.js | |-- routes | | `-- index.js | `-- views | `-- index.html |-- config | `-- AppConfig.js |-- lib | `-- customLib.js |-- vendor (or public) | |-- javascripts | | |-- jquery.js | `-- stylesheets | `-- StyleSheet.css |-- app.js (startup) `-- helpers `-- userHelper.js 

路线/ index.js:

 module.exports = function (app) { app.get('/', function (req, res) { res.json({ "Test": "Ok" }); }); app.get('/view', function (req, res) { res.render('index'); }); //Other routes here... } 

app.js:

 var express = require('express'); var mongoose = require('mongoose'); var app = express(); // view engine app.set('views', 'path/views')); // Set static/public folder app.use('/static', express.static('public')); /* you can also use `path.join(__dirname, 'folderName')` as standard reference to __dirname globals eg app.set('views', path.join(__dirname, 'views')); app.use('/static', express.static(path.join(__dirname, 'public'))); */ require('./routes')(app); var port = 8000; app.listen(port, function(error, response){ if (error){ console.log("Failed to run server!"); } }); module.exports = app; 

现在你可以运行命令node app.js &try http:// localhost:8000 /

试试这个,在你的index.js

 var router = express.Router(); router.get('/', function(req, res) { ... what ever you want }); module.exports = router; 

并在你的app.js

 var route = require('./routes/index.js'); app.use('', route); 

我希望这有帮助