我开始学习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)
项目结构:
|-- 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
e.g.
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
并尝试http:// localhost:8000 /
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句