Reputation: 1232
I am starting to learn node.js and I am using express.
My project structure is :
---CardDemo
-----view
-------index.html
-----server
-------controller
---------indexController.js
-------app.js
Now the codes :
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;
When I am doing localhost:8000/
I am getting :
Cannot GET /
What is going wrong ?
Upvotes: 1
Views: 1741
Reputation: 21649
What you are doing wrong is how & what you run as a startup file.
Try running (for existing files, sourcecode and folder structure):
node server/controller/indexController.js
(because you are exporting app not indexController)
Then try http://localhost:8000/
Project structure :
|-- 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
routes/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;
Now you can run command node app.js
& try http://localhost:8000/
Upvotes: 1
Reputation: 562
try this, in your index.js
var router = express.Router();
router.get('/', function(req, res) {
... what ever you want
});
module.exports = router;
and in your app.js
var route = require('./routes/index.js');
app.use('', route);
i hope this helps
Upvotes: 1