Priyabrata Priyabrata - 5 months ago 784
Node.js Question

Node.js throwing cannot GET / with express

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 ?

Answer

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/


Recommended

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/

Comments