I am facing a weird issue with angular and express,
I have a very simple routing on app.js as below :
app.get('/partials/:name', routes.partials);
app.get('*', routes.index);
also this is on my angular routerprovider :
$routeProvider.
when('/', {
templateUrl: '/partials/home'
}).
when('/contact', {
templateUrl: '/partials/contact'
}).
otherwise({
templateUrl: '/partials/error'
});
now the problem is, if I enter below invalid url, it goes to error page [OK]
http://www.devnest.io/someInvalidpath // it will go to /partials/error
But if I enter an invalid url with two level path (or more) page will hang [NOT OK]
http://www.devnest.io/someInvalidpath/AnotherInvalidPath // page will hang without error
and in the developer tools, it likes infinite loop and page call, like this picture :
also there is no error on node.js or angular ...
I am really confused, can anyone help me, on which part my routing is not correct ?
Thanks,
Try
app.use(routes.index);
instead of
app.get('*', routes.index);
Related
I am having an issue getting a partial to display using angular routing and express. I am trying to set things up so I can still use pug (formerly jade) to write shortform html. As far as I can tell, everything should be working, no errors, everything is pulling correctly. I have most other portions of the application working (api calls, controllers, etc.) My main page is as follows:
doctype html
html(ng-app='myapp')
head
base(href='/')
script(src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js")
script(src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-route.js")
body
header#main
.content(ng-view)
script(src="/js/app.js")
script(src="/js/controllers/adminController.js")
script(src="/js/routes.js")
Here is my routes file
angular.module('myapp')
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/admin', {
templateUrl: '/templates/admin',
controller: 'AdminController',
caseInsensitiveMatch: true
})
.otherwise({
template: '<h1>Page not found</h1>'
})
;
$locationProvider.html5Mode(true);
});
And finally, the express route:
router.get('/templates/:name', function(req, res, next) {
var name = 'templates/' + req.params.name;
console.log('Express: ' + name);
res.render(name, function(err, html){
//this callback function can be removed. It's just for debugging.
if(err)
console.log("Error: " + err);
else
console.log("We're good!");
res.send(html);
});
});
Lastly, here is the node server output:
Express: index
GET /admin 304 68.962 ms - -
GET /js/app.js 304 0.994 ms - -
GET /js/controllers/adminController.js 304 0.751 ms - -
GET /js/routes.js 304 14.590 ms - -
Express: templates/admin
We're good!
GET /templates/admin 304 368.081 ms - -
As you can see, the index loads, calls the partial, and the template is getting called and rendered just as you would expect.
The problem is ng-view is not getting replaced or updated. It all works just fine if I change the route to template instead of templateUrl, and just print out a line of text, so I know routing is working and this isn't an app configuration issue.
I've been stuck on this for a few days, and without any error messages, I am completely in the the dark as to why this doesn't work.
Additionally, when I check the following in my controller, I get the partial, so it is coming through properly:
angular.module('buriedcinema.controllers')
.controller('AdminController', ['$templateCache', function(Movies, Users, $templateCache){
console.log($templateCache.get('templates/admin'));
}
console:
<h1> this is my partial </h1>
Fixed by adding "controllerAs:" option to my routing and referring to my controller by the object name.
.when('/admin', {
templateUrl: 'templates/admin',
controller: 'AdminController',
controllerAs: 'adminCtrl',
caseInsensitiveMatch: true
})
The more technical explanation is that I wasn't instantiating an object with state, but trying to use my controller statically so it never updated. Hope this can help someone else.
I'm using ngRoute in my site, it work well on my computer (local) but on the server routing doesn't work. On my computer all my files are html, on the server i rename them as php. How can i fix it?
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider, $compileProvider) {
$routeProvider
.when("/", {
templateUrl : "pages/main.php",
controller: 'oneCtrl'
})
.when("/about", {
templateUrl : "pages/about.php"
})
.when("/news", {
templateUrl : "pages/news.php"
})
});
Based on the error messages you're getting (as you said in the comments), the Angular library is not being loaded. Double-check the URL. Also in the browser dev tools, check the Network tab and see what error it shows. Probably a 404 not found.
After checking your website and the line where you said the error was occurring (line 156 of route.js), change your code to this:
$('.counter-one span').eq(0).html(value1 + ' ');
$('.counter-two span').eq(0).html(value2 + ' ');
You did a search/replace for "html" to "php" but that also replaced the jQuery html() command. Just fix these two lines and you should be good.
I am trying to reload the page mannually from the browser but it doesn't work and says
Cannot GET /rate/4
My route:
angular.module('routing')
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/views/index.html'
})
.when('/rate/:cid', {
templateUrl: 'app/views/rate.html'
})
.otherwise({
'redirectTo': '/'
});
$locationProvider.html5Mode(true);
});
My assumption is that when I am reloading the main (index.html) is not loaded which is my base html file.
You do not have an angular problem, you have a server problem.
You're essentially working with a single page application.
When the server receives a request for rate/4 it must return index.html (or whatever the name that your main page is).
How you solve this will depend upon what platform you've implemented your server in.
For example, if you were running a node express server, you would have this kind of routing code:
app.get(/^\/rate\/.*/, function(req, res) {
// This matches a known pattern for a client-side route
res.sendFile(__dirname + '\\public\index.html');
});
I am using NodeJS + expressJS on server and AngularJS on client
AngularJS controller have the following routes:
app.config(function($routeProvider,$locationProvider) {
$routeProvider
.when('/field1/:id', {
controller: 'ctrl1',
templateUrl: "/view/mainpages/field1.html"
})
.when('/field2/:id', {
controller: 'ctrl2',
templateUrl: "/view/mainpages/field2.html"
})
........... many many
.when('/', {
controller: 'ctrl0',
templateUrl: "/view/mainpages/index.html"
})
.otherwise({redirectTo : '/'});
NodeJS static:
app.all('/*', express.static(__dirname + '/client'));
How to make the server redirects all the static pages on their paths relative to the root, in the case when the call goes directly through this link.
example:
server:3000/field1/23 must call server:3000/client/index.html
and index must upload JS like server:3000/js/cntr1.js
Upd: I found a solution to the problem. But it looks ugly as a crutch
app.get('/field1/([0-9]+$)', function(req, res, next) {
req.url='/index.html';
next();
});
app.use('/field1', express.static(__dirname + '/client'));
Perhaps there is a more elegant solution?
In expressjs, you can define the route using regular expression pattern matching. That means, anything under a specific set will always return the same page from the server side, and you will let angular decide what exactly to display or do which action.
Its not a great idea to redirect everything at / to same page as you need to manage your assets and they exist on the / part too , instead its a good idea to use a subdir which is easy to manage
Following snippet will redirect everything under the app path to the same page on server side
app.get('/app/*', function(req, res) {
res.send('app_index');
})
if you do not want to be limited to one app dir, instead you have a number of different root level dirs, all of which need to point to the same page, you can do something like this
app.get('/(app|server|client|form|dashboard)/*', function(req, res) {
res.send('app_index');
})
I have an angular app with a directory structure
app
..views
....partials
......main.jade
......foo.jade
....index.jade
and routes defined like:
'use strict';
angular.module('myApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'firebase',
'myApp.config'
])
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/partials/main',
controller: 'MainCtrl'
})
.when('/foo/:fooName', {
templateUrl: '/partials/foo',
controller: 'FooCtrl'
})
.otherwise({
redirectTo: '/'
});
});
I'm using express on the server side and the relevant code is:
// server.js
app.configure('development', function(){
app.use(express.static(path.join(__dirname, '.tmp')));
app.use(express.static(path.join(__dirname, 'app')));
app.use(express.errorHandler());
});
app.configure('production', function(){
app.use(express.favicon(path.join(__dirname, 'public/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);
//routes.js
exports.index = function(req, res){
res.render('index');
};
exports.partials = function(req, res){
var name = req.params.name;
res.render('partials/' + name);
};
The main route "/" loads fine and when i click to "/foo/bar" the partial view foo.jade loads as expected. However, when I try visiting "/foo/bar" directly in the URL i get a 404 response from Express "cannot GET /foo/bar" which makes sense since there's no route like this defined in express. However, I thought this was the whole point of defining the angular router..i.e. it's supposed to intercept this request and actually ask for "/partials/foo".
I tried adding
//redirect all others to the index (HTML5 history)
app.get('*', routes.index);
but it didnt solve the issue and seemed to be catching even the requests for static js assets and responding with the contents of index.html which is pretty bad.
I'm sure I'm doing something wrong. How can I fix things so that I can directly visit the URLs?
The reason routing is behaving like this is html5mode turned on.
Notice the line: $locationProvider.html5Mode(true);
You need to understand that when you try to access "/foo/bar" directly your browser sends HTTP GET request to this URL. When you try to access this url via link clicking, like you said, Angular is intercepting this action and calls History.pushState that only updates browser's link.
What you need to do in order to make html5mode routing work is implementing url rewrite. Every request has to be redirected to your index file that bootstraps AngularJS application, but this needs to be done on your server. Angular will render the desired page by itself.
Check out connect mod rewrite grunt task that does exacly that.
You can also you this middleware directly.