I'm trying work open page home of directory partials/home using ng-view and ng-view not working with express. A new page opens with render when acess http://localhost:3000/home. All routes defined for angular has no effect. I would like to know how to render my page partials/home.html in index.html using ng-view with express.
app.js
//módulos
var express = require('express');
var load = require('express-load');
var bodyParser = require('body-parser');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var server = require('http').Server(app);
var io = require('socket.io')(server);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//uncomment after placing your favicon in /public
app.use(favicon(__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')));
load('routes').then('controllers').into(app);
server.listen(3000);
console.log('Site no ar ...');
module.exports = app;
Routes Express - index.js
module.exports = function (app) {
app.get('/', function(req, res){
res.render('index');
});
app.get('/:name', function(req, res){
var name = req.params.name;
res.render('partials/' + name);
});
app.get('*', function(req, res){
res.render('index');
});
};
Routes Angular - Location: public/app/app.js
var app = angular.module('appSiteFio',['ngRoute']);
app.config(function($routeProvider, $locationProvider){
// remove o # da url
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl : 'index.html',
controller : 'mainController',
})
.when('/home', {
templateUrl : 'partials/home.html',
controller : 'homeController',
})
.otherwise ({ redirectTo: '/' });
});
I would suggest changing the index.js file to something like:
module.exports = function (app) {
app.use(express.static('/partials')); //here you can write your partials directory.
app.get('*', function(req, res){
res.render('index');
});
};
(Also change your templateUrl inside angular file with the partials prefix.);
that way angular will allways will be loaded and angular router will deal with all the views fetching from the static partials folder
Related
I'm using auth0 to act as my admin panel's login, and it's running great. A problem that I'm having is that in node, I cannot for some reason access 'req.user' as it returns unidentified. This is a pretty basic setup here. I have console logged req.headers and an authentication header is set.
Here is the node app.js file
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var Parse = require('node-parse-api').Parse;
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
// 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('/bower_components', express.static(__dirname + '/bower_components'));
app.Parse = new Parse(options.app_id, options.api_key);
app.use('/api', routes(app), expressJwt({secret: 'Mode'}));
app.all('/*', function(req, res) {
res.sendFile('index.html', { root: path.join(__dirname, '/public') });
});
module.exports = app;
Here is the AngularJS code.
var app = angular.module('EnragedGamers', ['angularMoment', 'ngRoute', 'auth0', 'angular-storage', 'angular-jwt'])
.config(function(authProvider, $routeProvider, $locationProvider, $httpProvider, jwtInterceptorProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'Home'
})
.when('/article/:article_id', {
templateUrl: 'article.html',
controller: 'Article'
})
.when('/admin-panel/login', {
templateUrl: 'admin-login.html',
controller: 'Admin-Login'
})
.when('/admin-panel', {
templateUrl: 'admin.html',
controller: 'Admin',
requiresLogin: true
});
authProvider.init({
domain: 'enragedgamers.auth0.com',
clientID: 'MpTkAl4eosjl3SB682ZGSSrJYi03QiZp',
loginUrl: '/admin-panel/login'
});
jwtInterceptorProvider.tokenGetter = ['store', function(store) {
// Return the saved token
return store.get('token');
}];
$httpProvider.interceptors.push('jwtInterceptor');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
})
.run(function($rootScope, auth, store, jwtHelper, $location) {
// This hooks al auth events to check everything as soon as the app starts
$rootScope.$on('$locationChangeStart', function() {
var token = store.get('token');
if (token) {
if (!jwtHelper.isTokenExpired(token)) {
if (!auth.isAuthenticated) {
auth.authenticate(store.get('profile'), token);
}
} else {
// Either show the login page or use the refresh token to get a new idToken
$location.path('/');
}
}
});
});
Here is the routes file code
var express = require('express');
var router = express.Router();
module.exports = function(app){
router.get('/admin/hello', function(req, res){
console.log(req.user)
res.status(201).json({'human': 'Hello'})
console.log(req.body);
});
return router;
}
It seems that you're missing your secret on the node side and the middle man for actually authenticating.
See https://github.com/auth0/express-jwt
var jwt = require('express-jwt');
app.use(jwt({ secret: 'your secret key here'}));
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 */
}
My application does not load templates in ng-view inside the index.thml.
I let my code here because i am lost.
app.js
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
// var $ = require('jquery');
// global.jQuery = $;
// var bootstrap = require('bootstrap');
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + 'views');
app.set('view engine', 'html');
var routes = require('./routes');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/views/index.html");
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Started Success http://localhost:' + server.address().port);
});
And angular route
angular.module('geradorContrato', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/contrato', {
templateUrl: '/public/views/contrato.html',
controller: 'ContratoController'
})
.when('/contratante', {
templateUrl: '/public/views/contratante.html',
controller: 'ContratanteController'
})
.when('/contratada', {
templateUrl: '/public/views/contratada.html',
controller: 'ContratadaController'
})
.when('/bemvindo', {
templateUrl: 'public/views/bemVindo.html',
});
});
But when i access http://localhost:3000/#/bemvindo
The page index.html loading success, but ngview not load and showing the message Cannot GET /public/views/bemVindo.html into console network chrome
Below is my index.html
<!DOCTYPE html>
<html ng-app="geradorContrato">
<head>
<meta charset="UTF-8">
<base href="/">
<link rel='stylesheet' href='/stylesheets/dist/css/bootstrap-theme.css'>
<link rel='stylesheet' href='/stylesheets/dist/css/bootstrap.css'>
<link rel="stylesheet" type="text/css" href="/stylesheets/mainStyle.css">
<script src="/javascript/lib/angular.js"></script>
<script src="/javascript/lib/angular-route.js"></script>
<script src="/javascript/lib/jquery.js"></script>
<script src="/javascript/lib/bootstrap.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script src="/javascript/main.js"></script>
<script src="/javascript/ContratoController.js"></script>
<title>Cadastro</title>
<head>
<body>
<div class="container">
<ng-view></ng-view>
</div>
</body>
</html>
and below is my page simple bemVindo.html
OLÁ SEJA VEM VINDO!
This is base structure my app
Structure
Sorry guys, if you do not understand something tell me pl
sorry for my english
Suggestions
deek:
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, 'public')));
var routes = require('./routes');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/', express.static(path.join(__dirname, '/public/views/index.html')));
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Started Success http://localhost:' + server.address().port);
});
Error Cannot GET /
path you have given must be wrong, check for the path where your file resides, try to console the path in the javascript console and provide the right path. "Cannot GET /public/views/bemVindo.html" means that the file bemVindo.html is not in the folder /public/views. It is not able to find the file hence showing this error.
Get rid of :
app.set('views', __dirname + 'views');
app.set('view engine', 'html');
Not needed....view engine html is default. Views folder isn't used.
EDIT: remove this too:
app.use(express.static(path.join(__dirname, 'public')));
Change this:
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/views/index.html");
});
To this:
app.use('/', express.static(path.join(__dirname, '/public/views/index.html')));
Let's express know this is a static directory where the html and supporting files are.
Express will treat it like a normal html directory and try to find an index file. From your index file, the angular will take over routing.
If you wanted to utilize express and templates for routing, the way you did it is best.
You set views folder if you want express to load template files from it but you have none.
You can mix and match with angular too.
So Im trying to work AngularJS and Node. I am trying to set up client side routing but Im having some problems.
EDIT
So I changed up some code following https://github.com/scotch-io/starter-node-angular that #PareshGami suggested. I get the URLS to be hit but now the actual content doesnt load.
Here is my updated Code:
server.js:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
app.use(bodyParser.json());
require('./server/routes')(app);
app.use('/js', express.static(__dirname + '/client/js'));
app.use('/views', express.static(__dirname + '/client/views'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/node_modules', express.static(__dirname +'/node_modules'));
app.listen(3000);
console.log('Im Listening...');
exports = module.exports = app;
my angular app.js:
(function (angular) {
'use strict';
var app = angular.module('eos', [
'ngRoute',
'ngResource',
'eos.opsCtrl',
'eos.dashboardCtrl'
]);
app.config(function ($routeProvider, $locationProvider){
$routeProvider.when(
'/',
{
templateUrl: 'views/dashboard.html',
pageName: 'Dashboard',
controller: 'dashboardCtrl'
}
);
$routeProvider.when(
'/ops',
{
templateUrl: 'views/ops.html',
pageName: 'Operations',
controller: 'opsCtrl'
}
);
$routeProvider.otherwise({redirectTo: '/'});
$locationProvider.html5Mode(true);
});
}(window.angular));
My routes.js (new):
var opsController = require('./controllers/opsController');
module.exports = function(app) {
//path.join(__dirname, 'client');
// server routes ===========================================================
// handle things like api calls
// authentication routes
app.get('/api/ops', opsController.list);
app.post('/api/ops', opsController.create);
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendFile('index.html', { root: './client' });
});
};
Then rest is identical. And suggestions on why it is not loading the content in the ng-view?
FINALLY GOT IT TO WORK! My server.js was set up wrong.
Here is the correct server.js. Notice position of:
require('./server/routes')(app);
it needed to be father down for what I assume is the compile sequence
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
methodOverride = require('method-override');
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use('/js', express.static(__dirname + '/client/js'));
app.use('/views', express.static(__dirname + '/client/views'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/node_modules', express.static(__dirname +'/node_modules'));
require('./server/routes')(app);
app.listen(3000);
console.log('Im Listening...');
exports = module.exports = app;
I was directed by PareshGami to look over this site 'setting-up-a-mean-stack-single-page-application'. After following that I was able to get the routing to work. The key to my problem was the ordering of my server.js file and the require('./server/routes')(app); part.
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.