angularjs pretty url is not working - angularjs

My problem is url is not working without # . Here is my code :
angular.module('Hiren', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/login.html',
controller: 'login'
})
.when('/redirect', {
templateUrl: 'partials/postLogin.html',
controller: 'postLogin'
});
$locationProvider.html5Mode(true);
});
When I try to browse the url example.com/redirect , it gives me 404 , but using hash ( example.com/#redirect) its perfectly working .

If you're getting a 404 in HTML5 mode you need to configure your server to serve your Angular application (usually index.html or app.html) when a 404 happens on the server. You don't mention what you're using for a server so I can't give specific instructions on how to do that. This is more a server configuration issue than an Angular one.
Edit now that server is known:
import SimpleHTTPServer, SocketServer
import urlparse, os
PORT = 3000
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
# Parse query data to find out what was requested
parsedParams = urlparse.urlparse(self.path)
# See if the file requested exists
if os.access('.' + os.sep + parsedParams.path, os.R_OK):
# File exists, serve it up
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);
else:
# redirect to index.html
self.send_response(302)
self.send_header('Content-Type', 'text/html')
self.send_header('location', '/index.html')
self.end_headers()
Handler = MyHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
Referenced SO answer.

Related

File serving using ngRoute in Angular with NodeJS server

I am trying to run AngularJS, using Angular Router, with a NodeJS server. I do not plan on serving the various views in Node, but instead I want to use the angular router. This first page is served correctly with no errors but when I try to click on another link, the browser displays the following
error code. Below is the relevant code from the server script, the routing script, and where the link in the HTML is.
HTML Link
<li>Add Workout</li>
Server.js
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/home.html'));
});
app.use(express.static('public'));
App.js
var app = angular.module("fitness2Uapp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "./app/views/home.html"
})
.when("/browse", {
templateUrl : "./app/views/browse.html"
})
.when("/add", {
templateUrl : "./add.html"
})
.when("/workout", {
templateUrl : "./app/views/workout.html"
});
});
Try putting in a "catch all" route that just redirects back to the main page. This will in turn allow the angular routing mechanism to kick in. Right now the problem is that it's trying to find an endpoint path of '/add' on the node server, but nothing is found. This should be the very last route established on your server.
I personally use AngularJS and had to do this, and everything works great. Not sure if this will also perform the same way as Angular2+
// Catch all if all other routes fail to match.
app.get('*', (req, res) => {
res.sendFile(path.resolve(`${__dirname}/path/to/home.html`));
});

Angular Route doesn't work (no error)

I am new to Angular and I need help with UI Router. I need to load mylink.html after clicking on link. Here is my code:
var app = angular.module('hollywood', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode({enabled: true, requireBase: false});
$stateProvider.state('mylink', {
templateUrl: 'mylink.html'
});
})
<a ui-sref="mylink">My Link</a>
<article ui-view></article>
What am I doing wrong? There is no error in console, except error after click:
XMLHttpRequest cannot load .... Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
The thing is file is local and I don't think I can set up CORS in these case.
https://jsfiddle.net/2q61mcp9/
Try using this code
var app = angular.module('hollywood', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$stateProvider.state('mylink', {
url: '/my-link',
templateUrl: 'mylink.html' // give absolute url like src/views/mylink/html
});
})
You missed to add url in state object
#Damian Are you serving your angular app via some kind of server (python ,node etc), or are you simply running the app via file system(Directly via open with browser option) in browser ?
If you are directly running it you are most likely to get this CORS issue as browsers dont allow resource sharing via file system for security issues.
My code is correct. I've deleted 'url' and run it on server. It work's.

Angular URL routing issue

So I needed to change my URL so that google analytics could track it. Google analytics wouldn't accept it with the "/#/" (hash) in the link. That said, I used Angular's locationProvider and revised my app routing with:
(function() {
'use strict';
angular
.module('mbapp')
.config(routerConfig);
/** #ngInject */
function routerConfig($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainController',
controllerAs: 'main'
});
$stateProvider
.state('steps', {
url: '/steps',
templateUrl: 'app/steps/steps.html',
controller: 'StepsController',
controllerAs: 'steps'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
}
})();
My URL is fine and changes it to http://website.com/steps rather than http://website.com/#/steps. However, now, if a user refreshes (f5) the link it then throw a 404 error and not sure why. Additionally, it seems that somehow this gets injected as the URL when the refresh is called "http://website/steps#/steps".
Any ideas on this?
Thanks much.
The problem is probably on the server side. You have to configure your server so it responds to every request with your html file. For example in express:
var app = require('express')();
app.configure(function(){
// static - all our js, css, images, etc go into the assets path
app.use('/assets', express.static('/assets'));
app.get('/api/users/:id', function(req, res){
// return data for user....
});
// This route deals enables HTML5Mode by forwarding missing files to the index.html
app.all('/*', function(req, res) {
res.sendfile('index.html');
});
});
When you reload the page, the request goes to the server side of your application, and it tries to resolve the url but it probably can't, because those routes only exists on the client side of your application.
Also it is a good idea to prefix every server side route with an /api route prefix, so you can easily distinguish between client side and server side routes.

All $http requests are returning -1

I am working on an app using ionic. Just today, all of my $http requests started failing by returning -1 status codes. This is happening when I run with ionic serve, ionic run browser and ionic emulate ios.
These $http requests are not necessarily remote, either. It's failing to load the HTML files inside of www/template. Any help with debugging would be greatly appreciated!
Some more details:
When running ionic serve, it loads index.html just fine, which loads my app.js. That in turn sets up an HTTP interceptor and loads the states using $stateProvider:
angular.module('starter', ['ionic', 'ngCordova', 'ionic.service.core', 'starter.controllers', 'setup.controllers', 'settings.controllers', 'history.controllers', 'graph.controller'])
...
.config(function ($stateProvider, $urlRouterProvider, $httpProvider, $analyticsProvider) {
...
$httpProvider.interceptors.push(['$q', '$location', function ($q, $location) {
return {
'request': function (config) {
// Setup authorization token...
return config;
},
'responseError': function (response) {
if (response.status === 401 || response.status === 403) {
$location.path('/login');
}
return $q.reject(response);
}
};
}]);
...
$stateProvider.state('login', {
cache: false,
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
cache: false,
controller: 'TabCtrl',
templateUrl: 'templates/tabs.html'
})
...
My browser's javascript console is filled with these errors:
ionic.bundle.js:25000 GET http://localhost:8100/templates/tabs.html net::ERR_EMPTY_RESPONSE(anonymous function) # ionic.bundle.js:25000sendReq # ionic.bundle.js:24793serverRequest # ionic.bundle.js:24503processQueue # ionic.bundle.js:29127(anonymous function) # ionic.bundle.js:29143$eval # ionic.bundle.js:30395$digest # ionic.bundle.js:30211$apply # ionic.bundle.js:30503(anonymous function) # ionic.bundle.js:32332completeOutstandingRequest # ionic.bundle.js:19194(anonymous function) # ionic.bundle.js:19470
ionic.bundle.js:25000 GET http://localhost:8100/templates/login.html net::ERR_EMPTY_RESPONSE(anonymous function) # ionic.bundle.js:25000sendReq # ionic.bundle.js:24793serverRequest # ionic.bundle.js:24503processQueue # ionic.bundle.js:29127(anonymous function) # ionic.bundle.js:29143$eval # ionic.bundle.js:30395$digest # ionic.bundle.js:30211$apply # ionic.bundle.js:30503(anonymous function) # ionic.bundle.js:32332completeOutstandingRequest # ionic.bundle.js:19194(anonymous function) # ionic.bundle.js:19470
When I drop a breakpoint in the interceptor, it intercepts the requests for these local HTML files and shows the response status code as -1.
UPDATE 1:
It keeps getting stranger... if I clear out the local storage, it works... once. I use local storage to store the logged in user account, so when I clear the storage and refresh, it successfully loads the pages. After I log in, all the requests stop working.
I spent a lot of time during investigation this issue and finally find out the problem.
In my case I have interceptor which adds Bearer Authorization data to each request, all worked amazing until this Bearer had small size, however I made design mistake and added a large amount of data to it after that problems started.
After minimizing Bearer request size all work as expected.

AngularJs routing, multiple requests in server

I want to use angularjs routing, I'm using but it's making extra requests in server side. Anyone know the solution of this problem, or I'm doing something wrong?
Client app.js
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode({enabled: true, requireBase: false})
$routeProvider.
when('/', {
templateUrl: '/tpl/main.tmp.html',
controller: 'MainCtrl'
})
.otherwise({redirectTo: '/'})
}])
//routes.js
app.get('/', function(req, res) {
console.log("test")
res.render(__dirname+'/public/tpl/index.html', siteConfig)
})
//output
//test
//test
//test
//test
Files:
models
public
|-css
|-js
|--app.js
|--angular.js
app.js
A few things may cause this, a closer inspection of both request packets might narrow down the cause. Some ideas to check for:
The browser keeps trying to fetch the site favicon because it can't find one
Fetching an image with a # in the URL (i.e. <img src="#"/>)
Meta refresh tag in the HTML
Web browsers may retry requests when the connection is closed before receiving a response

Resources