loopback angular 404 on refresh page - angularjs

I have create an application with loopback and angular but i have a problem. When i refresh the browser loopback give me a 404 url not Found.
Added base tag to index.html
<base href="/"/>
Set middlelware.json properly to serve static content:
"files": {
"loopback#static": {
"params": "$!../client"
}
Set HTML5 mode in angular router (I'm using ui-router)
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
I have yet deleted root.js from the project.
What i'm doing wrong? Thanks in advance

When you have enabled html5 mode/ push state mode ON in angularjs, this is a common scenario which your server should handle. If I understood your problem correctly, server returns 404 when you refresh the page which otherwise render fine if navigated from landing page. Let me know if this is the scenario:
Angular app lands into Home screen, say your_domain/
Navigate to some other page - your_domain/somepage (which will be your_domain/#somepage in case of hash bang mode)
Refresh the page -> throws 404
If the scenario which you face is like given above, then this is what happens:
Loads the home page -> angular is bootstraped and routing is set up
Navigates to "somepage" -> angular route handles this and show "somepage"
Refresh the page -> request hits the server and requests for your_domain/somepage - which is not available in server
server returns 404
How to handle this?
Do Url rewrite back to your_domain/ from server in case of 404. This will bootstrap the angular app and angular route will handle the request
More details here - https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
Copy pasting from above website
Apache Rewrites
<VirtualHost *:80>
ServerName my-app
DocumentRoot /path/to/app
<Directory /path/to/app>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
Nginx Rewrites
server {
server_name my-app;
root /path/to/app;
location / {
try_files $uri $uri/ /index.html;
}
}
Azure IIS Rewrites
<system.webServer>
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
Express Rewrites
var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
app.listen(3006); //the port you want to use
ASP.Net C# Rewrites
In Global.asax
private const string ROOT_DOCUMENT = "/default.aspx";
protected void Application_BeginRequest( Object sender, EventArgs e )
{
string url = Request.Url.LocalPath;
if ( !System.IO.File.Exists( Context.Server.MapPath( url ) ) )
Context.RewritePath( ROOT_DOCUMENT );
}

This can be frustrating BUT I got you covered.
This is tested and works on Nginx Ubuntu 14/16/18.. with angular 5+
Edit /etc/nginx/sites-enabled/default OR where ever you set your server settings.
This is the configuration that works:
server {
listen 80;
server_name <YOUR SERVER DOMAIN>;
access_log /var/log/nginx/nginx.vhost.access.log;
error_log /var/log/nginx/nginx.vhost.error.log;
index index.html index.htm;
location / {
root /wwweb/<location to angular dist>/dist;
try_files $uri $uri/ /index.html?$query_string;
}
}

I think that is because you are using $locationProvider.html5Mode(true); . try this $locationProvider.html5Mode(false);

Related

React Router - Navigating direct to route returns 404 [duplicate]

I have a node server like this:
var express = require('express');
var fs = require('fs');
var path = require('path');
var root = fs.realpathSync('.');
var app = express();
app.configure(function () {
app.use(express.static(__dirname + '/./'));
app.use(app.router);
});
app.get('/*', function (req, res) {
res.sendfile(path.join(root, './index.html'))
});
/*app.get('/dashboard', function (req, res) {
res.sendfile(path.join(root, 'index.html'))
});*/
app.listen(3000);
console.log('Listening on port 3000');
On the frontend, I am using backbone routes to route the application modules using HTML History API. So its always a well formatted URL. The problem occurs when I refresh the page. It works fine in local node server but when I deploy the application on microsoft azure cloud, the refresh creates a problem and it says, it cannot find a resource.
Is there anything specific to azure that I need to configure to make it understand that it should serve index.html on new requests instead of looking up for the resource?
In apache, we use .htaccess to do so but I have no idea about how to do the same on azure cloud!
Found the solution:
You need to have a webconfig file in the root for this to work. Azure internally has nothing but IIS to serve the files. If you observe closely, server.js is of no use once you deploy the application. IIS takes the control to serve the index.html file and hence you need to do something in the IIS configuration. Here is the Web.config (case sensitive) file that you need to put in the application root:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="redirect all requests" stopProcessing="true">
<match url="^(.*)$" ignoreCase="false" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" pattern="" ignoreCase="false" />
</conditions>
<action type="Rewrite" url="index.html" appendQueryString="true" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
You might try just use()ing a general middleware instead of a method-specific route:
app.use(function (req, res) {
res.sendfile(path.join(root, './index.html'));
});
As far as I know, Express currently does not support method-specific middleware (e.g. app.get(function(req, res) { ... })).
Also on an unrelated note, var root = fs.realpathSync('.'); is unnecessary since the global __dirname should get you the same value.

In AngularJS how to return 404 status code for any invalid URL?

Site is developed in AngualrJS and deployed on IIS web server. Where as we have only on page i.e. Index.html since it is single page application. For SEO purpose we are using prerender.io.
Added following code in web.config file to rewrite every single URL to root path
<rule name="AngularJS" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
Also handled all invalid URL into main.module.js with following code which will redirecting to error page.
$urlRouterProvider.otherwise(function ($injector, $location) {
var $state = $injector.get('$state');
var $rootScope = $injector.get('$rootScope');
var now = new Date(); now.setTime(now.getTime() + 1 * 1800 * 1000);
setContentCookie('dlerrorURL', $location.$$absUrl, now.toUTCString(), 'xyz.com')
$rootScope.error = true;
$state.go('app.newerror')
});
With the help of above code, status code 404 getting appeared on prerender.io, but if we look into netowrk tab in developer console it displays 200 status code for all invalid URL. Technically it is correct since we have added rule in web.config file to rewrite all the URL to root path.
After lots of finding we came to the solution that we have to keep all the URLs at server side by implementing Asp.Net MVC code and adding all routes into route.config file. So that if the URL is not matched it will return 404 status code.
But since we are having 300+ pages we are avoiding to implement the above solution. Is there any alternat way to get or set 404 status code for invalid URL.
As per my experience so far, I faced the same issue and we made few changes like this and it worked like charm for us!
Follow this steps:
Step 1:
Go to your RouteConfig.cs in your MVC application
you will see some route map like this..
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Now comment that default route and add an additional map route like this
routes.MapRoute(
name: "Home",
url: "dv/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "CatchAll",
url: "{*any}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
in above Map route name as HOME you will see something like dv you can replace it with any keyword for you like api or any initial of your project like abc or xyz we are doing this just to seperate the server route with angular route.
REMOVE THE CODE YOU HAVE WRITTEN IN YOUR WEB CONFIG FOR URL REWRITING.
FOR PRERENDER:
Add something like this in your web.config
<configSections>
<section name="prerender" type="Prerender.io.PrerenderConfigSection, Prerender.io, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
<prerender token="YOUR_TOKEN_HERE"></prerender>
and add prerender.io DLL to your MVC project.
Now, in system.web add something like this for prerender.
<system.web>
<httpModules>
<add name="Prerender" type="Prerender.io.PrerenderModule, Prerender.io, Version=1.0.0.2, Culture=neutral, PublicKeyToken=null"/>
</httpModules>
</system.web>
Now in the App_Start folder of your MVC application add this class name PreApplicationStartCode.cs.
public static class PreApplicationStartCode
{
private static bool _isStarting;
public static void PreStart()
{
if (!_isStarting)
{
_isStarting = true;
DynamicModuleUtility.RegisterModule(typeof(Prerender.io.PrerenderModule));
}
}
}
And in your AssemblyInfo.cs under Properties of your MVC app add something like this for prerender at the last line of the file.
[assembly: PreApplicationStartMethod(typeof(yourappnamespace.PreApplicationStartCode), "PreStart")]

Angular routeProvider without "#" [duplicate]

I want to enable HTML5 mode for my app. I have put the following code for the configuration, as shown here:
return app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix = '!';
$routeProvider.when('/', {
templateUrl: '/views/index.html',
controller: 'indexCtrl'
});
$routeProvider.when('/about',{
templateUrl: '/views/about.html',
controller: 'AboutCtrl'
});
As you can see, I used the $locationProvider.html5mode and I changed all my links at the ng-href to exclude the /#/.
The Problem
At the moment, I can go to localhost:9000/ and see the index page and navigate to the other pages like localhost:9000/about.
However, the problem occurs when I refresh the localhost:9000/about page. I get the following output: Cannot GET /about
If I look at the network calls:
Request URL:localhost:9000/about
Request Method:GET
While if I first go to localhost:9000/ and then click on a button that navigates to /about I get:
Request URL:http://localhost:9000/views/about.html
Which renders the page perfectly.
How can I enable angular to get the correct page when I refresh?
From the angular docs
Server side
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)
The reason for this is that when you first visit the page (/about), e.g. after a refresh, the browser has no way of knowing that this isn't a real URL, so it goes ahead and loads it. However if you have loaded up the root page first, and all the javascript code, then when you navigate to /about Angular can get in there before the browser tries to hit the server and handle it accordingly
There are few things to set up so your link in the browser will look like http://yourdomain.com/path and these are your angular config + server side
1) AngularJS
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true);
2) server side, just put .htaccess inside your root folder and paste this
RewriteEngine On
Options FollowSymLinks
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]
More interesting stuff to read about html5 mode in angularjs and the configuration required per different environment https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
Also this question might help you $location / switching between html5 and hashbang mode / link rewriting
I had a similar problem and I solved it by:
Using <base href="/index.html"> in the index page
Using a catch all route middleware in my node/Express server as follows (put it after the router):
app.use(function(req, res) {
res.sendfile(__dirname + '/Public/index.html');
});
I think that should get you up and running.
If you use an apache server, you might want to mod_rewrite your links. It is not difficult to do. Just a few changes in the config files.
All that is assuming you have html5mode enabled on angularjs.
Now. note that in angular 1.2, declaring a base url is not recommended anymore actually.
Solution for BrowserSync and Gulp.
From https://github.com/BrowserSync/browser-sync/issues/204#issuecomment-102623643
First install connect-history-api-fallback:
npm --save-dev install connect-history-api-fallback
Then add it to your gulpfile.js:
var historyApiFallback = require('connect-history-api-fallback');
gulp.task('serve', function() {
browserSync.init({
server: {
baseDir: "app",
middleware: [ historyApiFallback() ]
}
});
});
You need to configure your server to rewrite everything to index.html to load the app:
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#wiki-how-to-configure-your-server-to-work-with-html5mode
I wrote a simple connect middleware for simulating url-rewriting on grunt projects. https://gist.github.com/muratcorlu/5803655
You can use like that:
module.exports = function(grunt) {
var urlRewrite = require('grunt-connect-rewrite');
// Project configuration.
grunt.initConfig({
connect: {
server: {
options: {
port: 9001,
base: 'build',
middleware: function(connect, options) {
// Return array of whatever middlewares you want
return [
// redirect all urls to index.html in build folder
urlRewrite('build', 'index.html'),
// Serve static files.
connect.static(options.base),
// Make empty directories browsable.
connect.directory(options.base)
];
}
}
}
}
})
};
If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:
Set up your base href in your _Layout page: <head> <base href="/"> </head>
Then, add following in your angular app config : $locationProvider.html5Mode(true)
Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refresh will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all url
routes.MapRoute(
name: "App",
url: "{*url}",
defaults: new { controller = "Home", action = "Index" }
);
IIS URL Rewrite Rule to prevent 404 error after page refresh in html5mode
For angular running under IIS on Windows
<rewrite>
<rules>
<rule name="AngularJS" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
NodeJS / ExpressJS Routes to prevent 404 error after page refresh in html5mode
For angular running under Node/Express
var express = require('express');
var path = require('path');
var router = express.Router();
// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));
// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
res.sendFile(path.resolve('app/index.html'));
});
module.exports = router;
More info at: AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS
As others have mentioned, you need to rewrite routes on the server and set <base href="/"/>.
For gulp-connect:
npm install connect-pushstate
var gulp = require('gulp'),
connect = require('gulp-connect'),
pushState = require('connect-pushstate/lib/pushstate').pushState;
...
connect.server({
...
middleware: function (connect, options) {
return [
pushState()
];
}
...
})
....
I am using apache (xampp) on my dev environment and apache on the production,
add:
errorDocument 404 /index.html
to the .htaccess solve for me this issue.
For Grunt and Browsersync use connect-modrewrite here
var modRewrite = require('connect-modrewrite');
browserSync: {
dev: {
bsFiles: {
src: [
'app/assets/css/*.css',
'app/*.js',
'app/controllers/*.js',
'**/*.php',
'*.html',
'app/jade/includes/*.jade',
'app/views/*.html',
],
},
options: {
watchTask: true,
debugInfo: true,
logConnections: true,
server: {
baseDir :'./',
middleware: [
modRewrite(['!\.html|\.js|\.jpg|\.mp4|\.mp3|\.gif|\.svg\|.css|\.png$ /index.html [L]'])
]
},
ghostMode: {
scroll: true,
links: true,
forms: true
}
}
}
},
I solved to
test: {
options: {
port: 9000,
base: [
'.tmp',
'test',
'<%= yeoman.app %>'
],
middleware: function (connect) {
return [
modRewrite(['^[^\\.]*$ /index.html [L]']),
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static('app')
];
}
}
},
I'm answering this question from the larger question:
When I add $locationProvider.html5Mode(true), my site will not allow pasting of urls. How do I configure my server to work when html5Mode is true?
When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:
For Express Rewrites with AngularJS, you can solve this with the following updates:
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});
and
<!-- FOR ANGULAR ROUTING -->
<base href="/">
and
app.use('/',express.static(__dirname + '/public'));
I believe your issue is with regards to the server. The angular documentation with regards to HTML5 mode (at the link in your question) states:
Server side
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)
I believe you'll need to setup a url rewrite from /about to /.
We had a server redirect in Express:
app.get('*', function(req, res){
res.render('index');
});
and we were still getting page-refresh issues, even after we added the <base href="/" />.
Solution: make sure you're using real links in you page to navigate; don't type in the route in the URL or you'll get a page-refresh. (silly mistake, I know)
:-P
Finally I got a way to to solve this issue by server side as it's more like an issue with AngularJs itself I am using 1.5 Angularjs and I got same issue on reload the page.
But after adding below code in my server.js file it is save my day but it's not a proper solution or not a good way .
app.use(function(req, res, next){
var d = res.status(404);
if(d){
res.sendfile('index.html');
}
});
I have resolved the issue by adding below code snippet into node.js file.
app.get("/*", function (request, response) {
console.log('Unknown API called');
response.redirect('/#' + request.url);
});
Note : when we refresh the page, it will look for the API instead of Angular page (Because of no # tag in URL.) . Using the above code, I am redirecting to the url with #
I have found even better Grunt plugin, that works if you have your index.html and Gruntfile.js in the same directory;
https://npmjs.org/package/grunt-connect-pushstate
After that in your Gruntfile:
var pushState = require('grunt-connect-pushstate/lib/utils').pushState;
connect: {
server: {
options: {
port: 1337,
base: '',
logger: 'dev',
hostname: '*',
open: true,
middleware: function (connect, options) {
return [
// Rewrite requests to root so they may be handled by router
pushState(),
// Serve static files
connect.static(options.base)
];
}
},
}
},
I solved same problem using modRewrite.
AngularJS is reload page when after # changes.
But HTML5 mode remove # and invalid the reload.
So we should reload manually.
# install connect-modrewrite
$ sudo npm install connect-modrewrite --save
# gulp/build.js
'use strict';
var gulp = require('gulp');
var paths = gulp.paths;
var util = require('util');
var browserSync = require('browser-sync');
var modRewrite = require('connect-modrewrite');
function browserSyncInit(baseDir, files, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === paths.src || (util.isArray(baseDir) && baseDir.indexOf(paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
browserSync.instance = browserSync.init(files, {
startPath: '/',
server: {
baseDir: baseDir,
middleware: [
modRewrite([
'!\\.\\w+$ /index.html [L]'
])
],
routes: routes
},
browser: browser
});
}
I had the same problem with java + angular app generated with JHipster.
I solved it with Filter and list of all angular pages in properties:
application.yml:
angular-pages:
- login
- settings
...
AngularPageReloadFilter.java
public class AngularPageReloadFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.getRequestDispatcher("index.html").forward(request, response);
}
}
WebConfigurer.java
private void initAngularNonRootRedirectFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering angular page reload Filter");
FilterRegistration.Dynamic angularRedirectFilter =
servletContext.addFilter("angularPageReloadFilter",
new AngularPageReloadFilter());
int index = 0;
while (env.getProperty("angular-pages[" + index + "]") != null) {
angularRedirectFilter.addMappingForUrlPatterns(disps, true, "/" + env.getProperty("angular-pages[" + index + "]"));
index++;
}
angularRedirectFilter.setAsyncSupported(true);
}
Hope, it will be helpful for somebody.
Gulp + browserSync:
Install connect-history-api-fallback via npm, later config your serve gulp task
var historyApiFallback = require('connect-history-api-fallback');
gulp.task('serve', function() {
browserSync.init({
proxy: {
target: 'localhost:' + port,
middleware: [ historyApiFallback() ]
}
});
});
Your server side code is JAVA then Follow this below steps
step 1 : Download urlrewritefilter JAR Click Here
and save to build path WEB-INF/lib
step 2 : Enable HTML5 Mode $locationProvider.html5Mode(true);
step 3 : set base URL <base href="/example.com/"/>
step 4 : copy and paste to your WEB.XML
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
step 5 : create file in WEN-INF/urlrewrite.xml
<urlrewrite default-match-type="wildcard">
<rule>
<from>/</from>
<to>/index.html</to>
</rule>
<!--Write every state dependent on your project url-->
<rule>
<from>/example</from>
<to>/index.html</to>
</rule>
</urlrewrite>
I have this simple solution I have been using and its works.
In App/Exceptions/Handler.php
Add this at top:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Then inside the render method
public function render($request, Exception $exception)
{
.......
if ($exception instanceof NotFoundHttpException){
$segment = $request->segments();
//eg. http://site.dev/member/profile
//module => member
// view => member.index
//where member.index is the root of your angular app could be anything :)
if(head($segment) != 'api' && $module = $segment[0]){
return response(view("$module.index"), 404);
}
return response()->fail('not_found', $exception->getCode());
}
.......
return parent::render($request, $exception);
}

Loading the specific page on Browser Refresh. SPA AngularJS

I am creating a new Web API and Angular application. I want to know how we can handle routes on server side. Everything is working fine. I am using ui-router for routing, when i refresh browser that its giving me.
HTTP Error 404.0 - Not Found
I want to know how we can handle this.
Code for ui-router
$stateProvider.state('login', {
url: '/',
templateUrl: templatesDirectores.wmAccount + 'login.html',
controller: 'login-controller',
controllerAs: 'vm'
})
.state('register', {
url: '/register',
templateUrl: templatesDirectores.wmAccount + 'register.html',
controller: 'register-controller',
controllerAs: 'vm'
})
.state('forgetPassword', {
url: '/forgetpassword',
templateUrl: templatesDirectores.wmAccount + 'forget-password.html',
controller: 'forget-password-controller',
controllerAs: 'vm'
})
The view is loading fine as per the configuration, but when the URL is localhost:1235/register, it's loading fine first time but when I hit the refresh button I get 404 error.
This is occurring because you are using HTML5Mode = true in your Angular Application. Angular uses "hash" (/#register) routes to handle it's routing by default, in order to ensure that the browser does not perform a page reload from the server.
Using HTML5Mode, you can suppress the #, but at a cost. The browser must be HTML5 compliant, because HTML5Mode uses HTML Push State (HistoryAPI).
Also, your server must be configured to handle requests for routes which may exist in Angular but do not exist on the server. When you directly load a page, either by typing it in or by using refresh, a request is sent to the server, with a URL that the server may not know how to handle. Your server should be configured to return your Index.html page for any routes it does not expressly handle. This configuration varies per server.
Given you stated you are using IIS to host your site, something like the following would be necessary:
Web.config:
<system.webServer>
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
Essentially, for all routes (.*), if the request is not a file or a directory, rewrite the url to return the base URL /.
This can also be done in code, something similar to this:
Global.asax:
private const string ROOT_DOCUMENT = "/default.aspx";
protected void Application_BeginRequest( Object sender, EventArgs e )
{
string url = Request.Url.LocalPath;
if ( !System.IO.File.Exists( Context.Server.MapPath( url ) ) )
Context.RewritePath( ROOT_DOCUMENT );
}
There are a few other caveats here:
Each platform handles rewrites differently. In the case of IIS, the URL is rewritten, and the remainder of the route is lost. i.e. for localhost:1235/register, you will actually load localhost:1235/, and Angular will never receive the /register route. Essentially, all routes not known by IIS will return your app entry point.
You can set up multiple entry points to your app, but any in-memory references to variables, settings, etc. will be lost when moving from one entry point to another.
Given these two points, you should always consider any external URLs to be a fresh copy of your Angular application, and handle them accordingly.
Here's another way to reroute 404's to your SPA:
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404" subStatusCode="-1"/>
<error statusCode="404" prefixLanguageFilePath="" path="/spa-location.html" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I want to enable HTML5 mode for my app. I have put the following code for the configuration, as shown here:
return app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix = '!';
$routeProvider.when('/', {
templateUrl: '/views/index.html',
controller: 'indexCtrl'
});
$routeProvider.when('/about',{
templateUrl: '/views/about.html',
controller: 'AboutCtrl'
});
As you can see, I used the $locationProvider.html5mode and I changed all my links at the ng-href to exclude the /#/.
The Problem
At the moment, I can go to localhost:9000/ and see the index page and navigate to the other pages like localhost:9000/about.
However, the problem occurs when I refresh the localhost:9000/about page. I get the following output: Cannot GET /about
If I look at the network calls:
Request URL:localhost:9000/about
Request Method:GET
While if I first go to localhost:9000/ and then click on a button that navigates to /about I get:
Request URL:http://localhost:9000/views/about.html
Which renders the page perfectly.
How can I enable angular to get the correct page when I refresh?
From the angular docs
Server side
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)
The reason for this is that when you first visit the page (/about), e.g. after a refresh, the browser has no way of knowing that this isn't a real URL, so it goes ahead and loads it. However if you have loaded up the root page first, and all the javascript code, then when you navigate to /about Angular can get in there before the browser tries to hit the server and handle it accordingly
There are few things to set up so your link in the browser will look like http://yourdomain.com/path and these are your angular config + server side
1) AngularJS
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true);
2) server side, just put .htaccess inside your root folder and paste this
RewriteEngine On
Options FollowSymLinks
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]
More interesting stuff to read about html5 mode in angularjs and the configuration required per different environment https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
Also this question might help you $location / switching between html5 and hashbang mode / link rewriting
I had a similar problem and I solved it by:
Using <base href="/index.html"> in the index page
Using a catch all route middleware in my node/Express server as follows (put it after the router):
app.use(function(req, res) {
res.sendfile(__dirname + '/Public/index.html');
});
I think that should get you up and running.
If you use an apache server, you might want to mod_rewrite your links. It is not difficult to do. Just a few changes in the config files.
All that is assuming you have html5mode enabled on angularjs.
Now. note that in angular 1.2, declaring a base url is not recommended anymore actually.
Solution for BrowserSync and Gulp.
From https://github.com/BrowserSync/browser-sync/issues/204#issuecomment-102623643
First install connect-history-api-fallback:
npm --save-dev install connect-history-api-fallback
Then add it to your gulpfile.js:
var historyApiFallback = require('connect-history-api-fallback');
gulp.task('serve', function() {
browserSync.init({
server: {
baseDir: "app",
middleware: [ historyApiFallback() ]
}
});
});
You need to configure your server to rewrite everything to index.html to load the app:
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#wiki-how-to-configure-your-server-to-work-with-html5mode
I wrote a simple connect middleware for simulating url-rewriting on grunt projects. https://gist.github.com/muratcorlu/5803655
You can use like that:
module.exports = function(grunt) {
var urlRewrite = require('grunt-connect-rewrite');
// Project configuration.
grunt.initConfig({
connect: {
server: {
options: {
port: 9001,
base: 'build',
middleware: function(connect, options) {
// Return array of whatever middlewares you want
return [
// redirect all urls to index.html in build folder
urlRewrite('build', 'index.html'),
// Serve static files.
connect.static(options.base),
// Make empty directories browsable.
connect.directory(options.base)
];
}
}
}
}
})
};
If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:
Set up your base href in your _Layout page: <head> <base href="/"> </head>
Then, add following in your angular app config : $locationProvider.html5Mode(true)
Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refresh will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all url
routes.MapRoute(
name: "App",
url: "{*url}",
defaults: new { controller = "Home", action = "Index" }
);
IIS URL Rewrite Rule to prevent 404 error after page refresh in html5mode
For angular running under IIS on Windows
<rewrite>
<rules>
<rule name="AngularJS" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
NodeJS / ExpressJS Routes to prevent 404 error after page refresh in html5mode
For angular running under Node/Express
var express = require('express');
var path = require('path');
var router = express.Router();
// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));
// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
res.sendFile(path.resolve('app/index.html'));
});
module.exports = router;
More info at: AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS
As others have mentioned, you need to rewrite routes on the server and set <base href="/"/>.
For gulp-connect:
npm install connect-pushstate
var gulp = require('gulp'),
connect = require('gulp-connect'),
pushState = require('connect-pushstate/lib/pushstate').pushState;
...
connect.server({
...
middleware: function (connect, options) {
return [
pushState()
];
}
...
})
....
I am using apache (xampp) on my dev environment and apache on the production,
add:
errorDocument 404 /index.html
to the .htaccess solve for me this issue.
For Grunt and Browsersync use connect-modrewrite here
var modRewrite = require('connect-modrewrite');
browserSync: {
dev: {
bsFiles: {
src: [
'app/assets/css/*.css',
'app/*.js',
'app/controllers/*.js',
'**/*.php',
'*.html',
'app/jade/includes/*.jade',
'app/views/*.html',
],
},
options: {
watchTask: true,
debugInfo: true,
logConnections: true,
server: {
baseDir :'./',
middleware: [
modRewrite(['!\.html|\.js|\.jpg|\.mp4|\.mp3|\.gif|\.svg\|.css|\.png$ /index.html [L]'])
]
},
ghostMode: {
scroll: true,
links: true,
forms: true
}
}
}
},
I solved to
test: {
options: {
port: 9000,
base: [
'.tmp',
'test',
'<%= yeoman.app %>'
],
middleware: function (connect) {
return [
modRewrite(['^[^\\.]*$ /index.html [L]']),
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static('app')
];
}
}
},
I'm answering this question from the larger question:
When I add $locationProvider.html5Mode(true), my site will not allow pasting of urls. How do I configure my server to work when html5Mode is true?
When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:
For Express Rewrites with AngularJS, you can solve this with the following updates:
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});
and
<!-- FOR ANGULAR ROUTING -->
<base href="/">
and
app.use('/',express.static(__dirname + '/public'));
I believe your issue is with regards to the server. The angular documentation with regards to HTML5 mode (at the link in your question) states:
Server side
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)
I believe you'll need to setup a url rewrite from /about to /.
We had a server redirect in Express:
app.get('*', function(req, res){
res.render('index');
});
and we were still getting page-refresh issues, even after we added the <base href="/" />.
Solution: make sure you're using real links in you page to navigate; don't type in the route in the URL or you'll get a page-refresh. (silly mistake, I know)
:-P
Finally I got a way to to solve this issue by server side as it's more like an issue with AngularJs itself I am using 1.5 Angularjs and I got same issue on reload the page.
But after adding below code in my server.js file it is save my day but it's not a proper solution or not a good way .
app.use(function(req, res, next){
var d = res.status(404);
if(d){
res.sendfile('index.html');
}
});
I have resolved the issue by adding below code snippet into node.js file.
app.get("/*", function (request, response) {
console.log('Unknown API called');
response.redirect('/#' + request.url);
});
Note : when we refresh the page, it will look for the API instead of Angular page (Because of no # tag in URL.) . Using the above code, I am redirecting to the url with #
I have found even better Grunt plugin, that works if you have your index.html and Gruntfile.js in the same directory;
https://npmjs.org/package/grunt-connect-pushstate
After that in your Gruntfile:
var pushState = require('grunt-connect-pushstate/lib/utils').pushState;
connect: {
server: {
options: {
port: 1337,
base: '',
logger: 'dev',
hostname: '*',
open: true,
middleware: function (connect, options) {
return [
// Rewrite requests to root so they may be handled by router
pushState(),
// Serve static files
connect.static(options.base)
];
}
},
}
},
I solved same problem using modRewrite.
AngularJS is reload page when after # changes.
But HTML5 mode remove # and invalid the reload.
So we should reload manually.
# install connect-modrewrite
$ sudo npm install connect-modrewrite --save
# gulp/build.js
'use strict';
var gulp = require('gulp');
var paths = gulp.paths;
var util = require('util');
var browserSync = require('browser-sync');
var modRewrite = require('connect-modrewrite');
function browserSyncInit(baseDir, files, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === paths.src || (util.isArray(baseDir) && baseDir.indexOf(paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
browserSync.instance = browserSync.init(files, {
startPath: '/',
server: {
baseDir: baseDir,
middleware: [
modRewrite([
'!\\.\\w+$ /index.html [L]'
])
],
routes: routes
},
browser: browser
});
}
I had the same problem with java + angular app generated with JHipster.
I solved it with Filter and list of all angular pages in properties:
application.yml:
angular-pages:
- login
- settings
...
AngularPageReloadFilter.java
public class AngularPageReloadFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.getRequestDispatcher("index.html").forward(request, response);
}
}
WebConfigurer.java
private void initAngularNonRootRedirectFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering angular page reload Filter");
FilterRegistration.Dynamic angularRedirectFilter =
servletContext.addFilter("angularPageReloadFilter",
new AngularPageReloadFilter());
int index = 0;
while (env.getProperty("angular-pages[" + index + "]") != null) {
angularRedirectFilter.addMappingForUrlPatterns(disps, true, "/" + env.getProperty("angular-pages[" + index + "]"));
index++;
}
angularRedirectFilter.setAsyncSupported(true);
}
Hope, it will be helpful for somebody.
Gulp + browserSync:
Install connect-history-api-fallback via npm, later config your serve gulp task
var historyApiFallback = require('connect-history-api-fallback');
gulp.task('serve', function() {
browserSync.init({
proxy: {
target: 'localhost:' + port,
middleware: [ historyApiFallback() ]
}
});
});
Your server side code is JAVA then Follow this below steps
step 1 : Download urlrewritefilter JAR Click Here
and save to build path WEB-INF/lib
step 2 : Enable HTML5 Mode $locationProvider.html5Mode(true);
step 3 : set base URL <base href="/example.com/"/>
step 4 : copy and paste to your WEB.XML
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
step 5 : create file in WEN-INF/urlrewrite.xml
<urlrewrite default-match-type="wildcard">
<rule>
<from>/</from>
<to>/index.html</to>
</rule>
<!--Write every state dependent on your project url-->
<rule>
<from>/example</from>
<to>/index.html</to>
</rule>
</urlrewrite>
I have this simple solution I have been using and its works.
In App/Exceptions/Handler.php
Add this at top:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Then inside the render method
public function render($request, Exception $exception)
{
.......
if ($exception instanceof NotFoundHttpException){
$segment = $request->segments();
//eg. http://site.dev/member/profile
//module => member
// view => member.index
//where member.index is the root of your angular app could be anything :)
if(head($segment) != 'api' && $module = $segment[0]){
return response(view("$module.index"), 404);
}
return response()->fail('not_found', $exception->getCode());
}
.......
return parent::render($request, $exception);
}

Resources