Issue after remove (#) hashbangs from routing in angular-ui-router - angularjs

I have remove (#) hashbangs by $locationProvider.html5Mode(true) in ui-route.
and set <base href="/public/">
when I have tried to localhost:59940/public/#/home url # is remove and url look localhost:59940/public/home and getting home view.
but when I have tried localhost:59940/public/home url. I have getting 404 Not Found error.
help me for getting home view when try to access localhost:59940/public/home in browser.

The problem is that the browser resolves urls before your angular app responds, and indeed the resource for that route is not there. The solution I have used is to make your 404 route return the index.html page and use ui-router to handle real 404 cases. But another idea is to match all of the client routes to routes on your server which return the index.html.

To enable $locationProvider.html5Mode in angular, you also need to some side server changes.
Other then your static assets and apis path, all other routes should server index.html(your main SPA page) only.
See below code.
This is how you can do it in node.js using express server.
var app = require('express')();
app.configure(function() {
// Static files - all js, css, images, etc go into the static path
app.use('/static', express.static('/static'));
// If a static file is invalid so we send 404
app.use('/static', function(req, res, next) {
res.send(404);
});
// This route deals enables HTML5Mode by forwarding missing files to the index.html
app.all('/*', function(req, res) {
res.sendfile('index.html');
});
});
app.listen(3000);

Related

How to do serverside HTML5 mode URL Rewriting with NodeJS and browserSync

How to remove #! getting added to url in my AngularJS application?
I have tried:- $locationProvider.html5Mode(true).hashPrefix('!'); and adding <base href="/"> but to no avail. When I navigate to a particular url, #! disappears but when I tried to reload, it gives the error:- Cannot GET.
So I looked online, and found out that doing above is only half of the solution. We also need to rewrite the logic on server side as well. So I am using NodeJS and browserSync package to fire up localhost. So what is the solutioin to this?
Note:- My backend and frontend code are separate and both handle routing.
There is a option in Browsersync called single which serves the index.html as a fallback if the url does not exist.
Serve an index.html file for all non-asset routes. Useful when using client-routers
See documentation:
https://www.browsersync.io/docs/options#option-single
browserSync.init({
server: {
baseDir: 'dist',
},
single: true
});

Express Rewriting for Clean URLs in MEAN Stack Application with no index.html

Like many other clean angular URL rewrites, upon refreshing the page on a clean URL like localhost:3000/profile I get the GET /profile 404 error. I have been trying to use an Express Rewrite to send the index.html file, but as far as I know, I don't have an index.html to send, as it's not rendered until the index.js route.
I tried the following in my app.js:
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
and receive Error: ENOENT: no such file or directory, stat 'C:\xampp\htdocs\healthyu\healthyu\index.html'
My directory looks like this image here, and I can see there is no index.html file in the root directory. I have tried views/index.html, views/index.ejs, and views/index with no luck, and views/index.ejs actually prompted a download when I refreshed the page.
Is there a way to use Express to successfully rewrite the URLs, or will I be more successful with a mod-rewrite in an .htaccess file?
So what I needed to do was change all of my server requests that were API requests to use the /api prefix, so get /api/posts in order to reduce conflicts with get /posts which was the original API call and view name along with other conflicts.
My index.html is generated in my express routes/index.js file so I just needed to make sure I used that file whenever I tried to navigate to a different URL than the home entry point. The relevant parts of the code looked like the following:
var index = require('./routes/index');
var users = require('./routes/users');
app.use('/', index);
app.use('/api', index);
app.use('/users', users);
app.use("/*", index);

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>

How can i make my AngularJS website crawled on google?

I want to remove # from my angularjs app, I am developing an website, I think it may help to make SEO friendly website, May be i am wrong, Please help
Thanks
I agree with Joe Lloyd for the way to remove the # from your url but it won't help you to make your angularjs website crawlable.
Check out the following steps :
Configure the html5mode
config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
Add <meta name="fragment" content="!"> to your pages so the google bot knows to add the ?_escaped_fragment_= at the end of your request.
Handle the ?_escaped_fragment_=on the server side and serve a static snapshot of the requested html page (phantomjs can make the job) so the bot will index the rendered version of the html page.
Populate your sitemap.xml and send it to google using www.google.com/webmasters/
Have fun !
Config
To remove the # in your url you need to add this to your main module. You put the app into html5 mode.
//This config is used to remove the # in the html
app.config(["$locationProvider", function($locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}]);
Server Side (NodeJS)
This will have a server side effect when you hit refresh you need to add an extra route that is able to find the new url. this will work in your express js app.js file. Where the public folder contains your angular app and you have your index.html file in there
// ### CATCH REFRESH TO INDEX ###
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('public/index.html', { root: __dirname });
});

AngularJS and Express Routing issue

I'm using AngularJS and ExpressJS and having an issue with routing. I saw many other posts but none of those solutions seemed to work. Here is my routes in Express:
module.exports = function(app, auth) {
//Api routes
var mycontroller = require('../app/controllers/mycontroller');
app.get('/api/dostuff/:id', mycontroller.getBlockByHash);
//Home route
app.get("/", function(req, res) {
res.render('index');
});
};
When I go to my root /, everything works as expected. ExpressJS serves up my index and angular picks up the rest. When I click a link /blocks, it works as expected since AngularJS picks up the route. But when I refresh, I get a 404 not found error.
I tried app.get('*' instead, but that gives me a completely different error where nothing loads.
I'm using Jade to create the basic page structure with Express. My Express config is:
app.use(express.favicon());
app.use(express.static(config.root + '/public'));
When using html5Mode the documentation says:
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
What it doesn't mention is:
You should exclude static assets like scripts/styles/images/fonts etc.
You should also exclude your Restful API.
Your case:
The error you got there is express serving html into script tags and the browser fails to parse them as a valid javascript.
Use express.static to serve static assets and then use app.get('*', for redirecting all other requests to your angular.js entry point (index.html).
express.js middleware order do counts!
express.static must be declared before app.router
Node.js / Express.js - How does app.router work?

Resources