Node.js browser error Cannot GET/ - javascript

I'm quite new to Node, I've been following a tutorial to build a simple server that serves dynamic pags with some basic routes but keep getting the Error: Cannot GET/ after running node server.js and calling localhost:3300 on the browser. My routes are defined externally and initialized using a routes.initialise() as follows:
//routes.js
var home = require('../controllers/home'),
image = require('../controllers/image'),
express = require('express');
module.exports.initialize = function(app, router) {
//var router = express.Router();
router.get('/', home.index);
router.get('/images/:image_id', image.index);
router.post('/images', image.create);
router.post('/images/:image_id/like', image.like);
router.post('/images/:image_id/comment', image.comment);
app.use('/', router);
};
I've searched far and wide but no solution forthcoming. I'm really frustrated and will need some help here.
I have a server.js that creates the server:
//server.js
var express = require('express'),
config = require('./server/configure'),
app = express();
app.set('port', process.env.PORT || 3300);
app.set('views', __dirname + '/views');
app = config(app);
var server = app.listen(app.get('port'), function() {
console.log('Server up: http://localhost:' + app.get('port'));
});
and a configure.js that configures the server:
//configure.js
var path = require('path'),
routes = require('./routes'),
exphbs = require('express3-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
module.exports = function(app) {
app.engine('handlebars', exphbs.create({
defaultLayout: 'main',
layoutsDir: app.get('views') + '/layouts',
partialsDir: [app.get('views') + '/partials']
}).engine);
app.set('view engine', 'handlebars');
app.use(morgan('dev'));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes.initialize(app, new express.Router());
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
return app;
};
also two files, home.js and image.js which are supposed to provide the default routes from configure.js:
//home.js
module.exports = {
index: function(req, res) {
res.send('The home:index controller');
}
};
//image.js
module.exports = {
index: function(req, res) {
res.send('The image:index controller ' + req.params.image_id);
},
create: function(req, res) {
res.send('The image:create POST controller');
},
like: function(req, res) {
res.send('The image:like POST controller');
},
comment: function(req, res) {
res.send('The image:comment POST controller');
}
};
Anytime I try to GET any of the links on the browser it returns the Cannot GET/ error. Any help will be greatly appreciated.
Thank you so much :)

I actually copied your exact code and it worked as you expect, though frankly it's got a bunch of indirection and at least one deprecated module. Maybe you have a PORT environmental variable set, and so the app isn't actually running on 3300?

Related

How to use express middleware to handle all routes?

I have issue setting up routes for user in below code, I want to use express middleware and trying routes using app.use.
index.js is invoking user controller method once api's is being called So in below code i am trying to post data api/users from client but it returns 404.
How can i fix this issue using below routes setup ?
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
var db = require('./config/db');
var port = process.env.PORT || 8080;
mongoose.connect(db.url);
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app); // configure our routes
require('./config/express')(app);
app.listen(port);
console.log('listening on port ' + port);
exports = module.exports = app;
app > routes.js
module.exports = function(app) {
app.use('api/users', require('./api/user'));
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
// res.sendFile(path.join(__dirname, ''../public/views/index.html''));
});
};
config > express.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
// import cookieParser from 'cookie-parser';
// import errorHandler from 'errorhandler';
var path = require('path');
// import lusca from 'lusca';
var config = require('./db');
var mongoose = require('mongoose');
//var mongoStore = connectMongo(session);
module.exports = function(app) {
// app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
}
User index where i will handle all crud operation for user
app > api > user > index.js
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
router.get('/', controller.index);
router.post('/',controller.create);
module.exports = router;
1st:
To handle all request
Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
app.use(function(req,res)
{
res.sendfile('./public/views/index.html');
console.log("Not found....I will handle *unhandle* rout here for you");
})
// app.get('*', function(req, res) use the above function instead of this
But this function at the end so it will only excute when no route path found to the app object.
Express documentation
2nd:
To handle createuser
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
// you must define route which you want to handle in user file
router.get('/api/user', controller.index);
router.post('/',controller.create);
module.exports = router;
Update working example with some explanation
Your app.js file
var express=require('express')
var app=express()
app.use('api/user',require('./user'))
app.use('/',require('./user'))
app.use(function(req,res)
{
res.sendfile('stack10.html')
console.log("Not found....I will handle *unhandle* rout here for you");
})
app.listen(8080,function()
{
console.log("server listening on port 8080")
})
user.js
var express = require('express')
var router = express.Router()
var app=express()
router.get('/api/user', function(req, res) {
res.send('respond for ..../api/user')
});
router.get('/',function (req,res) {
res.send('respose for ..../')
})
module.exports = router;
Your app.use will be app.use(api/user) while in user will be router.get(/api/user) so when u try http://127.0.0.1:8080/api/user
your response will be respond for ..../api/user

Node.JS and AngularJS Routes with API routes

So I am using Node.JS with Express as my backend and my servlet for API. I'm using AngularJS as my front end.
Through many Google searches, I finally solved my problem of using ngRoute with AngularJS and Node.js. And ended up with this:
var index = require('./routes/index');
var auth = require('./routes/auth');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.use('/api/auth', auth);
app.use('/', index);
app.use('*', index);
This is of course an excerpt of my app.js file at the root of my project.
Now when I make a call to my /api/auth/ I get told that node.js can't find my view. If I remove the app.use('*', index) the API works again but 'ngRoute' doesn't work.
How can I get to a point where both are working together? I also want to keep the address bar url as clean as possible.
My project was started with a call to yo node using yeoman if that helps any in the file/folder structure of my application.
Update
I'm not getting any answers or comments so maybe providing my full app.js file will be helpful and help me figure this out. Here it is.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var auth = require('./routes/auth');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api/auth', auth);
app.use('/', index);
app.use('*', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Update 2
I have come to notice that the statement "ngRoute doesn't work" is vague. If I remove app.use('*', index) I receive this error if I try to go to an address other than the base address. I also receive this error when trying to access theapi/auth
Error: Failed to lookup view "error" in views directory "/Users/mitch/websites/splatform/views"
Update 3
The index.js file that my routes in app.js refer to includes this as well.
app.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
But, API calls shouldn't be going to the index.js File. Should be going to Auth.js.
Update 4
As requested, here is my $routeProvider from AngularJS.
$routeProvider
.when('/', {
templateUrl: 'templates/home.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load ('frontStyles');
}]
}
})
.when('/app/login', {
templateUrl: 'templates/login.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load ('appStyles', 'appScripts');
}]
}
})
.when('/app/dashboard', {
templateUrl: 'templates/dashboard.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load ('appStyles', 'appScripts');
}]
}
})
.otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
Also here is a simple run down of my file structure
app.js
routes
--auth.js
--index.js
views
--index.html ( angularJS Base )
public
--directives
--fonts
--images
--javascripts
--stylesheets
--templates ( Views that angularjs uses in `ng-view`
Call api's routes first then angularjs index.
For example: routesWeb.js
'use strict';
var express = require('express');
var path = require('path');
module.exports = function(app) {
var path_web = path.resolve(__dirname, '..');
var path_origin = path.resolve(__dirname, '../../');
app.use('/scripts',express.static(path_web + '/scripts'));
app.use('/pages',express.static(path_web + '/pages'));
app.use('/node_modules',express.static(path_origin + '/node_modules'));
app.route('/*')
.get(function(req, res){
res.sendFile(path_web + '/pages/ng-index.html');
});
}
pessoaRota.js
'use strict';
module.exports = function(app) {
var pessoasCtrl = require('../controllers/pessoasController');
app.route('/api/pessoas')
.get(pessoasCtrl.obter_todos_pessoas);
app.route('/api/pessoas/:pessoaId')
.get(pessoasCtrl.obter_pessoa_por_id);
app.route('/api/pessoasFeias')
.get(pessoasCtrl.obter_pessoas_feias);
};
server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
app.use(bodyParser.json());
app.use(cookieParser());
var server = app.listen(port, function(){
var host = server.address().address;
var port = server.address().port;
console.log("Aplicação está on nesse endereço http://%s:%s", host, port)
});
require('./api/routes/pessoaRota.js')(app);
require('./web/routes/routesWeb.js')(app);
For more go here.

Node + Express JS API is not working

I'm a beginner in node.js but I try a little harder to setup a structure in node + express js.I start doing with the front-end and separate API structure.I put a single app.js for both API and front-end.But my API is not working. it gives error Cannot GET /api/users when i call http://localhost:3000/api/users. please help
api
-controllers
-helpers
-middlewares
-models
-routes.js
app.js
controllers
helpers
middlewares
models
node_modules
package.json
public
views
app.js
var express = require('express')
, app = express()
, bodyParser = require('body-parser')
, port = process.env.PORT || 3000
var path = require('path');
app.set('views', path.join(__dirname, 'views/'));
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(require('./controllers'))
var routes = require('./api/routes');
app.use('/api', routes);
app.listen(port, function() {
console.log('Listening on port ' + port)
})
routes.js
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
module.exports = function (app) {
app.get('/users', usersController.getUser);
};
module.exports = router;
users.js(controller)
module.exports = {
getUser: function (req, res) {
console.log("sdfdsfdsfsd");
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({"msg": "welcome user"}));
}
}
In your routes.js file you are exporting two things. Try to only export the router
var express = require('express')
, router = express.Router()
var usersController = require('./controllers/users');
router.get('/users', usersController.getUser);
module.exports = router;

Express routing error Cannot Get /api/name

Having some trouble setting up the restful API for my express app.
Here is my app.js:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override');
routes = require('./routes'),
api = require('./routes/api'),
port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(bodyParser.urlencoded({extended: true}));
// Page Routes
app.get('/', routes.index);
app.get('/partials/:filename', routes.partials);
// // API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
In /routes/api.js I have the following test function:
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
Currently I get the following error when i go to http://my_ip/api/name
Cannot GET /api/name
Any ideas?
Thanks
The following code is working for me. I think there is some issue with your routes package. Can you share the code of 'routes' package and file structure ?
app.js
var express = require('express'),
app = express(),
routes = require('./routes');
api = require('./routes/api'),
port = process.env.PORT || 3000;
// Page Routes
app.get('/', routes.index);
// API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
/routes/api.js
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
/routes.js
exports.index = function (req, res) {
res.json({
name: 'Index'
});
};

Error: .get() requires callback functions but got a [object Undefined]

I am new to node & express and I tried different variations and couldn't figure out why. If I map app.get ('/') to just contentHandler then it works fine. But if I map app.get ('/) to contentHandler.displayWelcomePage then I get the above error. Thanks for looking.
Here is my structure:
app.js
routes/index.js
routes/content.js
app.js
var express = require('express')
, app = express()
, routes = require('./routes')
, http = require('http')
, path = require('path')
, mongoose = require ('mongoose')
, db = mongoose.connection
;
db.on ('error', console.error);
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use (app.router);
routes(app, db);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
routes/index.js
var contentHandler = require('./content');
//this is what I need to add, see my notes below var aHandler = new contentHandler();
module.exports = exports = function (app, db) {
console.log ('inside routes/index.js');
app.get ('/', contentHandler.displayWelcomePage);
//instead of using contentHandler, use aHandler.displayWelcomePage
};
routes/content.js
function contentHandler (req, res, db) {
console.log ('Inside contentHandler');
res.render('index', {layout: false, title: "Jade is three."});
this.displayWelcomePage = function (req, res) {
return res.render('index', {layout: false, title: "Welcome to Jade"});
};
};
module.exports = contentHandler;

Categories