Page reload doesn't work when removing # from angular urls - angularjs

I'm trying to remove # from my angularjs urls using
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
and <base href="/"> in my index.html and i have changed the hrefs in my partials from #/abc to /abc
it works fine when navigating through links within the site, however except my home page, on every other page, when i try to reload the page or copy and paste the link(and hit enter) it gives me error. i have done alot of search online with no luck. i'm hoping someone here has already gone through this and can help me.
thanks

So if you are using jade you shall do the following:
app.get('/', index);
// while index is defined in routes.js and jade is defined as template engine
If you're using angularjs templating engine with normal html files, do the following:
exports.index = function(req, res) {
res.sendfile(__dirname + "/public/index.html");
};
app.get('/', index);

Related

Base tag breaks script links in Angular HTML5 mode

Problem
After setting a base tag to run Angular 1.x in HTML5 mode, the browser (Chrome) makes requests to the wrong path for scripts when accessing the app by navigating directly to localhost:3000/resource/id.
Details
I have an Angular 1 app that I have recently set to run in HTML5 mode, like so:
$locationProvider.html5Mode(true);
I have included a base tag in the head of index.html like so:
<base href="/">
I have set up my express routes so that a request for (for example) http://localhost:3000/album/38ad87f will return index.html, like so:
.use('/', express.static(__dirname + '/crate-frontend/app'))
// Playlist endpoints
.use('/api/playlists', playlistRoutes)
// Album endpoints
.use('/api/album', albumRoutes)
// Artist endpoints
.use('/api/artist', artistRoutes)
// Track endpoints
.use('/api/tracks', trackRoutes)
// User endpoints
.use('/api/user', userRoutes)
// Discogs proxy endpoints
.use('/api/discogs', discogsRoutes)
// Youtube proxy endpoints
.use('/api/youtube', youtubeRoutes)
// Search endpoints
.use('/api/search', searchRoutes)
// For serving up crate-frontend/app/index.html
.all('/*', function(request, response){
response.sendFile(__dirname + '/crate-frontend/app/index.html' );
})
Now, when I go to the home page, and navigate around, everything works fine. BUT if I refresh the page that is not the root OR a copy/paste a URL like http://localhost:3000/album/38ad87f into a new window, it breaks. I can see that it receives index.html, but then when the browser requests each of the linked scripts, for example:
<script src="app.js"></script>
it actually makes a request to http://localhost:3000/album/app.js, which returns index.html.
Can someone tell me what I've missed / am doing wrong?
Try to include your ressources with an absolute path and you will be fine for all time.
<script src="/app.js"></script>

UI router + node/express JS page reloading unwantedly

I have a strange issue with UI router and Express interacting together.
I've looked for solutions everywhere but nothing seems to be completely fixing the issue working.
When my app is in my /public folder and when i navigate to / it works fine and the url is getting changed as i click links.But whenever i go directly to /random/path ( ui-sref="post/new"> ), it get intercepted by nodejs and say that this route doesn't exist.
I've fixed that issue using from a topic on that issue :
app.use('/', express.static(__dirname + '/public'));
app.use(function (req, res) {
res.sendFile(__dirname + '/public/');
});
And now everything is working fine whenever i navigate directly to the path i want.
Now there is a new issue where the whole page will reload on every path change instead of just behaving like a client side app should and just load the view + controller.
The strange thing is that it's working as expected for 2 or 3 path.
Can anyone help ?
edit :
angular.module('App').config(function($stateProvider, $locationProvider,$urlRouterProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider
.state('posts-new', {
url:'/post/new',
templateUrl: 'tmpl1.html'
})
.state('posts', {
url:'/posts',
templateUrl: 'tmpl2.html'
});
});
I've also tried with both base url / and <base href="/index.html">
Alright, so your NodeJS route not existing is because of your route.
It works fine for / because it interprets that as /public/index.html.
If you then try and load /post/new, it looks for /public/post/new/index.html - and doesn't find it.
Fix below should work for you.
app.use(function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
Then, you'll need a slightly separate way of serving your templates - basically as static files! I'd personally suggest you use a simple folder for templates, as shown below. Make sure this is above your catchall route above.
app.use('/templates', express.static('/public/templates'));
Oh, and finally - you'll want your <base> tag set to /.

creating my first nodejs,mongo, express angularjs app

I am setting up my first angularjs webapp using nodejs.
The one part i am not sure how to do is how to include my angularapp.js in my index.html?
currently i have
/public
index.html
/javascript
webapp.js ( my angular app js file)
/routes
myroute.js
app.js (my nodejs app )
my myroute.js has and it loads fine
router.get('/', function(req, res, next) {
res.sendFile(path.resolve('public/index.html'));
});
the problem is that i am note sure how to load my webapp.js
in my index.html i have
<script src = "/public/javascript/webapp.js"></script>
And this does not load. So what is the best way to do this. Should i create
a route for everything in /public/javascript/
how do other people do this or what is the best practice
thanks for any help
update....
i added the following to myroute.js
router.get(/javascript/, function(req, res, next){
res.sendFile(path.resolve('public/javascript/webapp.js'));
});
and the javscript file now loads but this is not the way to do it.
I got it now. I've been searching and looks like for security reasons you need to serve the javascripts and other files you wish to allow access to as static files. On app.js add this :
app.use("/static",express.static(__dirname+"/public/javascript"));
Where "static" is just a virtual path you create for an specific folder. Then change src on script:
http://localhost:port/static/webapp.js
or
/static/webapp.js
It worked for me
For more details you should check this out:
http://expressjs.com/es/starter/static-files.html

Html5Mode - refreshing the angularjs page issue

I am working on an angularJS app, which has URLs in the format (in dev) -
http://localhost:6001/#/home/index
http://localhost:6001/#/content/index
As this app, will also be available on desktop browser, I wanted the URLs to be without '#', so I added this in my app's config section -
$locationProvider.html5Mode(true);
Which works fine and URLs don't show '#'. But there is a problem now. On refreshing a particular page in browser, now I get this error -
Cannot GET /home/index
Are there any other changes required to get this working?
Note: This app is using cordova CLI and is hosted on a Node.js server.
Try to put in your as your route:
app.get(*, function(req,res) {
//return the main index file
});
This will cause any unmatched route to serve the index page and from there angular take care of this route.
Try this:
Make sure you have these lines in your server.js file
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public.build'));
app.use(function(req, res) {
res.sendFile('index.html', { root: __dirname + "/public.build" });
});
Why so? Please read here - https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
The first step resulted in my app in the following console.log message:
Resource interpreted as Stylesheet but transferred with MIME type
text/html: "http://localhost:8080/board/css/style.css".
As you can see, the styles are trying to load from non-existent path (/board/ folder is not present in the app, it's one of the states in ui-router).
To fix it I replaced the following line
<link rel="stylesheet" href="css/style.css">
with this one:
<link rel="stylesheet" href="/css/style.css">

angular ui-router, html5 mode always refreshes to /

I am trying to use html5mode in angular, so that I can bookmark a page like http:/myhost/products (where /products is a route defined by$stateProviderRef.state(xxx) ).
To that end I've
added $locationProvider.html5Mode(true) to my app config
added 'base href="/"' (with the <>) to my index.html
added the catch all rewrite to my server.js in node.js
app.get('*', function(req, res) {
res.redirect('/');
});
restarted the node server
so what happens is that the app starts ok, all navigation works, I can go to http://myhost/products and everything works well.
However, if I press refresh at this point, I am redirected back to the index page. Looks to me as if ui-router is either losing the path (/products) or I have missed something in the config / setup
I have been browsing through the questions on StackOverflow until my eyes are bleeding, but all of the solutions to similar problems are things that I've already done (base=, redirect etc)
Anyone else has this problem and solved it ? Would be much appreciated if you could share your findings.
Thanks
You shouldn't redirect in server like that
app.get('*', function(req, res) { res.redirect('/'); });
Instead, send same index.html
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
Take a look at this generator for more
https://github.com/DaftMonk/generator-angular-fullstack/blob/master/app/templates/server/routes.js

Resources