Can't navigate directly to URL Angular UI Router - angularjs

This is my router file:
it's nested inside a require.js block and configured to work with Jade templates
define([
'./app',
'angular.uirouter'
], function(app, angularUIRouter) {
"use strict";
// ROUTES
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
// loads url from the index
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
$stateProvider
.state('dashboard', {
url:'/dashboard',
views: {
'core' : {
templateUrl: '/articles/dashboard'
}
}
})
}]);
});
And this is my Express.js router file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('main', {
title: 'Express'
});
});
router.get('/dashboard', function(req, res) {
console.log("/dashboard requested");
});
router.get('/articles/:name', function (req, res) {
var name = req.params.name;
res.render('articles/' + name);
});
module.exports = router;
When I go to localhost:3000/dashboard, it's making a GET request to the server. How do I configure Angular UI Router to handle GET requests instead of the server?
Note: I can still go to localhost:3000/articles/dashboard and see the dashboard. Also,
a(ui-sref="dashboard")
loads the dashboard correctly.

Neither angular nor ui router can not handle server GET. Angular $locationProvider html5Mode solves only client-side setting - url does not contain # and location controls also path part in URL.
Html5 mode requires server side configuration. Every requests must return application entry point - usually index.html.
For example
router.get('/dashboard', function(req, res) {
res.sendfile('path-to/index.html');
});

Related

Routing working locally, not on Heroku servers

My AngularJS application won't route to /login when accessing /login directly. It will route to /login if I first access / then route from / to /login.
It is working on my local environment but not with Heroku servers. Are there some settings I have to configure on the Heroku server?
I am using angular-ui-router to route to different states throughout my application.
My app.js config snippet looks like this:
angular.module('app', [
angularUiRouter
])
.config(($stateProvider) => {
"ngInject";
$stateProvider
.state("home", {
url: "/",
template: "<home></home>"
})
.state("login", {
url: "/login",
template: "<login></login>"
});
})
Answering my own question.
Since the setup on this application is using MEAN stack, we have to also add routing from server side to client.
For all templates in AngularJS there has to be a routing from Express to AngularJS to index.html
for all templates and routings created in angular we need to get the request and send index.html in response
when we use angularjs stateProvider to route in Angularjs.., we have to also add routing to /dist/index.html from server side.
$locationProvider.html5Mode(true).hashPrefix('!'); has to be defined in app.js on AngularJS side
A snippet of my Server.js file:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/dist'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/dist/index.html');
});
app.get('/login', function(req, res){
res.sendFile(__dirname + '/dist/index.html');
});

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.

SPA Design & Routing: AngularJS, TaffyDB, & ExpressJS

I have been using AngularJS for a few months now. I have been using a Java backend for all of my AngularJS applications. Now I'd like to learn how to program full-stack JavaScript applications. I've never programmed in NodeJS.
The current design of my app has Angular taking care of all the routing, which is what I am most comfortable with. However, I am not sure if that is good design when using NodeJS and Express on the backend. In the past, my backend has been responsible for exposing a REST API that my frontend could leverage, and manipulating JSON data. I didn't use it for anything else.
This is how Angular is managing the routing in my full-stack JS app
(function()
{
angular
.module('passGen', [
'ui.router',
'ngAnimate',
'passGen.generator',
'passGen.registration',
'passGen.tabs',
'passGen.main'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider)
{
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'partials/main.html'
})
.state('registration', {
url: '/register',
templateUrl: 'partials/registration.html'
})
.state('products', {
url: '/products',
});
}]);
})();
I want to add user registration functionality to the application. This is where TaffyDB and Node come into play. I'd like the backend to maintain and serve all of the user registration data in order to avoid overloading the frontend.
Right now all I'm trying to do is post some data in NodeJS to the /products route, but it's not doing anything. This is reflected in the comments.
server.js
(function()
{
// modules
var express = require('express');
var path = require('path');
var TAFFY = require('taffy');
var app = express();
app.use(express.static('src/app'));
var products = TAFFY([{
'item':1,
'name':'Shark'
}]);
// I don't think this is necessary
app.get('/#/home', function(req, res)
{
res.sendFile(path.join('/index.html'));
});
// Not doing anything, also doesn't work with the '/products' path
app.post('/#/products', function(req, res)
{
res.send(products);
console.log(products);
});
app.listen(8878);
})();
Perhaps I need to take a deeper look at ExpressJS routing documentation, or refine my Google queries.
I have some questions:
Should I use AngularJS or ExpressJS to handle the routing?
If I can use AngularJS for the routing, then should I be able to use ExpressJS to handle HTTP requests?
Why isn't app.post working in server.js?

How can I refresh routes with angular.js, ui-router, and node.js

I have an angularjs and nodejs app with ui-router that works well from the home page. The problem is I cannot refresh any other state or type another state url in the browser and go directly to it.
I have nodejs respond to requests for the state urls with the index.html file
app.get('/*', function (req, res) {
res.sendfile('client/index.html');
});
The app gets index.html and requests all the scripts from index.html but for some reason it adds the state url in front of the request. For instance in my index.html header there is this script
<link href="css/normalize.css" rel="stylesheet">
If I refresh the browser from a state other than home, then the script is requested like this:
GET /albums/css/normalize.css
edit: I fixed this problem ^^ by adding a '/' in the link like so: href="/css/normalize.css".
Now the index file loads but angular does not send a get request for the partial file associated with the state. It only loads the index.html file.
This is my app.js file for angular
angular.module('myApp', [
'ngTouch',
'ui.router',
'ngRoute',
'ngAnimate',
'myApp.controllers',
'myApp.directives',
'myApp.restServices',
'ui.bootstrap',
'ngCookies',
'ngResource',
'ngSanitize',
'snap',
'angular.css.injector'
]).
config(['$stateProvider', '$httpProvider', '$urlRouterProvider', '$locationProvider','snapRemoteProvider', function ($stateProvider, $httpProvider, $urlRouterProvider, $locationProvider, snapRemoteProvider) {
snapRemoteProvider.globalOptions.disable = 'right';
$httpProvider.interceptors.push('authInterceptor');
$urlRouterProvider.otherwise("home");
$stateProvider
.state('home', {url: "/",templateUrl: "partials/home.html",controller: 'homeCtrl'})
.state('albums', {url: "/albums",templateUrl: "partials/albums/albums.html",controller: 'albumsCtrl'})
.config(['$locationProvider', function ($locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
}]);
This is my node server
var express = require('express'),
url = require('url');
path = require('path'),
bodyParser = require('body-parser'),
directory = require('./routes/directory'),
app = express();
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://curtwphillips.com');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Accept, X-api-key, X-auth-token, Content-Type, Content-Length');
res.setHeader('Access-Control-Allow-Credentials', true);
if (req.headers && req.headers.authorization) { delete req.headers.authorization; }
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(path.join(__dirname, '/client')));
app.use(function(req, res, next){
console.log('%s %s', req.method, req.url);
next();
});
app.get('/*', function (req, res) {
res.sendfile('client/index.html');
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
});
I figured out the problem. I was naming some of my states with the same names as folders in my client folder.
When I tried to refresh the 'albums' state, shown here:
.state('albums', {url: "/albums",templateUrl: "partials/albums/albums.html",controller: 'albumsCtrl'})
the url "/albums" was matched to my "/client/albums" directory by this node code
app.use(express.static(path.join(__dirname, '/client')));
I fixed the issue by renaming my folders so they don't match the angular urls. This way the catchall code sends index.html. Hopefully this helps someone out there.

AngularJS: Relative link paths are broken when html5mode(true) is on

I've been searching and I've found "solutions" to this problem, yet I still can't get this to work right.
The Scenario:
I'm building an Angular (version 1.2) website with the UI Router and running it on a Node server on localhost. I'm trying to make it have "pretty" url's with the $locationProvider and by turning html5(true) on. My website works fine when clicking through it, but when I try to navigate to a relative link path or refresh the link path the page breaks. I also intend to deploy this webapp to Heroku when completed:
RELATIVE LINK PATH:
http://localhost:8000/locksmith-services
PAGE OUTPUT RESULT
Cannot GET /locksmith-services
Steps I've taken:
1.) In my "index.html" < head >, I've set my base url to:
<base href="/"></base>
2.) In my app.js file (for Angular), I have it written as follows:
// App Starts
angular
.module('app', [
'ui.router',
'ngAnimate',
'angular-carousel'
])
.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function($urlRouterProvider, $stateProvider, $locationProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'pages/home.html',
controller: 'homeCtrl'
})
.state('services', {
url: '/locksmith-services',
templateUrl: 'pages/locksmith-services.html',
controller: 'servicesCtrl'
})
.state('locations', {
url: '/locksmith-locations',
templateUrl: 'pages/locksmith-locations.html'
})
.state('payment', {
url: '/locksmith-payment',
templateUrl: 'pages/locksmith-payment.html'
})
// use the HTML5 History API
$locationProvider.html5Mode(true);
}])
3.) In my navigation, I have my html written as:
<div class="wrapper">
<a ui-sref="home">
<img src="images/logo.png" class="logo" alt="Austin Texas Locksmith" />
</a>
</div>
<nav class="row navigation">
<a class="mobile33" ui-sref="services" ui-sref-active="active" class="active">Services</a>
<a class="mobile33" ui-sref="locations" ui-sref-active="active">Locations</a>
<a class="mobile33" ui-sref="payment" ui-sref-active="active">Payment</a>
</nav>
4.) My server.js file (node server)
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/front'));
var port = process.env.PORT || 8000;
app.listen(port);
What would be the best solution? Thanks in advance for your help.
Thanks to #trehyu for helping me get to this answer.
Like he wrote, I needed something setup on my server.js file that redirects the user to my "index.html" file.
So depending on your file structure...
BEFORE (not working)
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/front'));
var port = process.env.PORT || 8000;
app.listen(port);
AFTER (working)
var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/front/js'));
app.use('/build', express.static(__dirname + '/../build'));
app.use('/css', express.static(__dirname + '/front/css'));
app.use('/images', express.static(__dirname + '/front/images'));
app.use('/pages', express.static(__dirname + '/front/pages'));
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('/front/index.html', { root: __dirname });
});
var port = process.env.PORT || 8000;
app.listen(port);
I hope this helps someone else!
When HTML5mode is set to true, you need something setup on your server that automatically redirects the user to your index page, so that the AngularJS UI Router can take over from there.
The reason for this is that without the hash (#) in the URL, it takes it as a literal URL and tries to navigate there when you refresh or paste the url directly.
I'm not very familiar with Node so not sure how you would do that, but there is a FAQ page on the UI Router GitHub that should help you get started: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode

Resources