I get an error Cannot Get /. this is my folder structure
This is the route.js file:
//route.js
'use strict';
var app = require('../../config/express');
var router = app.Router();
/* Get Home Controller */
var homeController = require('../controllers/index');
router.get('/index', homeController.index); //it isn't recognized
app.use('/', router);
'use strict';
/*
* GET /
* Home Page
*/
exports.index = function(req, res){
res.render('index', {
'pageTitle': 'Express page'
});
};
'use strict';
/* Import Express module */
var express = require('express');
var path = require('path');
//var bodyParser = require('body-parser');
/* Import env config parameters */
var settings = require('./env/settings');
/* Create express server */
var app = express();
/* Settings Application */
app.set('port', settings.port);
app.set('views', path.join(__dirname, '/frontend/views'));
app.set('view engine', 'jade');
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/assets'));
module.exports = app;
I know that it is a problem on routing but I have tried to fix it
Cannot Get / is exactly what is says. You have not defined any routes that match that path. You have defined /index, but not /, and they are two different URLs. index.html-style behavior is not provided by Express in routes. It is available with the static-file middleware if you want it though.
So change it to:
router.get('/', homeController.index);
or if you also want /index to work, just do both:
router.get('/', homeController.index);
router.get('/index', homeController.index);
Related
I am new to Node.js. After watching many explanatory videos and and reading the Node.js docs, I started developing the site while respecting an MVC structure. The node server seems to work but the display on the front shows Cannot GET /. Here is the Browser Screenshot and the MVC structure of the project
index.js code :
'use strict';
/* eslint-env node, es6 */
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
const PORT = process.env.PORT || 4242;
app.use('/', require('./routes/home_route'));
app.listen(PORT, () => {
console.log(`serveur démaré: localhost:${PORT}`);
});
home_controller.js code :
'use strict';
const homeView = (req, res) => {
res.render("home_view", {
} );
}
module.exports = { homeView };
home_route.js code :
'use strict';
const express = require('express');
const { homeView } = require('../controllers/home_controller');
const router = express.Router();
router.get('/home', homeView);
module.exports = router;
And home_view.ejs is just html. I don't understand where my mistake is, the code seems correct to me. Thank you in advance for your answers.
The problem is that you don't have any route handler for /. You are only handling /home. What you are saying with this line app.use('/', require('./routes/home_route')); is that every time I receive a request on /, I passe it to that router inside home_route.js, which only handles /home.
One way to solve this is to redirect the request you get on / to /home which is already handled. For that change home_route.js to:
const express = require('express');
const { homeView } = require('../controllers/home_controller');
const router = express.Router();
router.get('/home', homeView);
router.get('/', (req, res)=> res.redirect('/home')); // line I added
module.exports = router;
This is my index.js file in my ./home directory:
var express = require('express');
var control = require('./controllers/todoController');
var app = express();
//set up template engine
app.set('view engine', 'ejs');
//static files
app.use(express.static('./public'));
//fire controllers
control();
//listen to port
app.listen(3000);
console.log('You are listening to port 3000');
This is my todoController.js file in my ./home/controllers directory:
module.exports =function(app){
app.get('/quiz', function(req, res){
res.render('quiz');
});
};
The error that is shown is:
TypeError : cannot read property 'get' of undefined
Use the router module of expressjs
const express = require('express');
const router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
var token = req.body.token('token');
if(!token)
{
res.render('error', {
'message': "You must indicate a Token"
});
}
});
module.exports = router;
Then, just import it on your app.js main file :
app.use('/', tokenHandler);
You must give your app to controller as parameter
Try this in your index.js file
//fire controllers
control(app);
app.js
var express = require("express");
var app = express();
var path = require('path');
var db = require('./db');
var bodyParser = require('body-parser');
app.listen(80);
app.set('view engine', 'jade');
app.set('views', "./views");
// app.get('/', _GetMainPage);
// app.get('/sites', _GetSites);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true })); // Support encoded bodies
app.use(bodyParser.json()); // Support json encoded bodies
app.use(require('./controllers'));
./controllers/index.js
var express = require('express');
var router = express.Router();
router.use('/', require('./sites'));
router.use('/site', require('./site'));
module.exports = router;
./controllers/sites.js
var express = require('express');
var router = express.Router();
var site = require('../models/site');
router.get('/', function(req, res) {
site.getAll(function(err, rows){
if(err) {
res.send(err);
return;
}
res.render('sites', { sites : rows });
});
});
./controllers/site.js
var express = require('express');
var router = express.Router();
var site = require('../models/site');
router.get('/site', function(req, res) {
// console.log("get /site received. req.body: " + req.body);
res.render('site', {
site: {
name : req.params.name
}
});
});
module.exports = router;
When I request localhost/site I get a response saying:
Cannot GET /site
localhost/ works perfectly
I have been looking at this for a while and can't find the problem yet. If there is anything I can add, let me know. Thanks.
Thank you to the person that commented with the answer:
What happens if you navigate to /site/site? Your site.js route is relative to the route you provided in use. So it should be router.get('/' ... not router.get('/site' ...
The ./controllers/site route is already being routed to /site. On top of this I was calling router.get('/site', ...). This means it was actually routing to /site/site.
The solution is to just use router.get('/', ...) in the site.js file instead.
This really helped me, thank you.
Basically, the root path in the sub-app is defined in your core app where you mount it via the app.use() method.
the best example I can find from app.mountpath docs is here:
https://expressjs.com/en/4x/api.html#express.router
The app.mountpath property contains one or more path patterns on which a sub-app was mounted.
var express = require('express');
var app = express(); // the main app
var admin = express(); // the sub app
admin.get('/', function (req, res) {
console.log(admin.mountpath); // /admin
res.send('Admin Homepage');
});
app.use('/admin', admin); // mount the sub app
It is similar to the baseUrl property of the req object, except
req.baseUrl returns the matched URL path, instead of the matched
patterns.
If a sub-app is mounted on multiple path patterns, app.mountpath
returns the list of patterns it is mounted on, as shown in the
following example.
var admin = express();
admin.get('/', function (req, res) {
console.log(admin.mountpath); // [ '/adm*n', '/manager' ]
res.send('Admin Homepage');
});
var secret = express();
secret.get('/', function (req, res) {
console.log(secret.mountpath); // /secr*t
res.send('Admin Secret');
});
admin.use('/secr*t', secret); // load the 'secret' router on '/secr*t', on the 'admin' sub app
app.use(['/adm*n', '/manager'], admin); // load the 'admin' router on '/adm*n' and '/manager', on the parent app
The common middle for expressjs is the Route() middleware, but now I'm dropping jade and using handlebars. Handlebars itself have it ways to define the route. Because of that I may mess up my controllers inside my app.js.
Below is my app.js, any idea how can I split the route to a new file?
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.get('/',function(req,res){
res.render('index');
});
var port = Number(process.env.PORT || 3000);
app.listen(port);
Something like this?
//exported routes in ./routes/index.js
var routes = require('./routes');
//invoke routes
routes(app);
and routes file
module.exports = function(app) {
app.post('/etc', function(req,res) {
/* do route stuff */
});
/* other stuff goes here */
}
I am trying to make a basic application using the MEAN Stack.
I have been struggling for the past hour or so to make a basic route work, but I fail miserably.
Whenever I access my application on / the template provided to the Angular route will not render the template, even if I can manually access it at templateUrl in the browser.
This is my code:
express.js
var express = require('express'),
bodyParser = require('body-parser'),
session = require('express-session'),
logger = require('morgan'),
cookieParser = require('cookie-parser');
module.exports = function(app, config){
app.set('views', config.rootPath + '/server/views');
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({secret: 'contact demo'}));
app.use(express.static(config.rootPath + '/public'));
};
routes.js
var mongoose = require('mongoose'),
Contact = mongoose.model('Contact');
module.exports = function(app, router) {
router.get('/partials/*', function(req, res) {
res.render('../../public/app/' + req.params[0]);
});
router.get('*', function(req, res) {
res.render('index');
});
app.use('/', router);
};
server.js
// Module Dependencies
var express = require('express'),
mongoose = require('mongoose');
// Initialize Express Application
var app = express(),
env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
// Config Parameters
var config = require('./server/config/config')[env];
// Invoke Express Config File
require('./server/config/express')(app, config);
// Invoke Mongoose Config File
require('./server/config/mongoose')(config);
// Invoke Routes File
require('./server/config/routes')(app, express.Router());
app.listen(config.port);
console.log('Listening on port ' + config.port + '...');
app.js
angular.module('demo', ['ngResource', 'ngRoute'])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {templateUrl: '/partials/main/main'});
$locationProvider.html5Mode(true);
});
layout.jade
doctype
html
head
title Contact Management Application
link(rel="stylesheet" href="/vendor/bootstrap/dist/css/bootstrap.min.css")
link(rel="stylesheet" href="/css/style.css")
body(ng-app="demo")
block main-content
include scripts
index.jade
extends ../includes/layout
block main-content
h1 Hello World
section.content
div(ng-view)
main.jade
section.content
h1 I should be rendered!
EDIT
This is my folder structure:
--public/
--app/
--main/
--main.jade
--app.js
--css/
--vendor/
--server/
--config/
--express.js
--routes.js
--includes/
--layout.jade
--scripts.jade
--views/
--index.jade
--server.js
Where are you calling the REST commands in your angular code? It seems like you're just navigating to a different page within the app but you aren't telling it to pull from the server.