Node.js not loading AngularJS views - angularjs

I was developing an web application just like that:
- project
--- app
------ controllers
------ views
------ app.js
--- public
------ assets
--------- css
--------- js
--------- img
--- index.html
... inside my index.html I had the basics html, link, script tags. All that loading the angular application and everything was working fine.
But now, I need to loading all the application using Node.js.
So first I move the index.html to public/ and created a new file.
index.js (Node.js)
app.use("/", express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Runing the Node.js I got at the browser console:
GET http://localhost:3000/app/views/layouts/public.html 404 (Not Found)
This is how I load my angular views
app.config(function($urlRouterProvider, stateHelperProvider) {
$urlRouterProvider.otherwise('/');
$urlRouterProvider.when('', '/');
stateHelperProvider.state({
name: 'public',
title: 'Home',
url: '/',
controller: 'PublicCtrl',
templateUrl: '/app/views/layouts/public.html',
data: {
requireLogin: false
}
})
.state({
name: 'private',
controller: 'PrivateCtrl',
templateUrl: '/app/views/layouts/private.html',
data: {
requireLogin: true
},
children: [
{
name: 'browse',
title: 'Home',
url: '/browse',
templateUrl: '/app/views/browse/index.html',
controller: 'BrowseCtrl'
}
]
});
});

Try using
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
This worked for me, I've only used app.use for the static content (as you are) like css and js.
Also you've written it as though your index.html is in your public directory
Hope this helps

Related

Can we use client-side angularjs routing using ui router with expressjs server side routing in nodejs. Below is the example

Example:
var bodyparser=require('body-parser');
var fs=require('fs');
var express=require("express");
var myApp = express();
var MongoClient=require('mongodb').MongoClient;
var assert=require('assert');
var url = 'mongodb://localhost:27017/dbname';
var ObjectId=MongoClient.ObjectID;
var http=require('http');
myApp.use(express.static("."));
myApp.use(bodyparser.json());
myApp.listen(5000);
I am using server(apache or node) to load only index file from there after am using ui-router to make it a SPA which is working well wen run in apache server but this is not working wen ran on node:
the index is being loaded correctly but following url :
http://localhost:5000/Test/#/dashboard
throws the message : "Cannot GET /Test/" in node server, How to make the Routing to work correctly in expressjs
$urlRouterProvider.otherwise('/login');
var DASHBOARD_ROOT = 'templates';
$stateProvider.state('index', {
url: '/login',
templateUrl: 'login.html',
controller: 'employeeInfoCtrl'
});
$stateProvider.state('dashboard', {
abstract :true,
url: '/dashboard',
templateUrl: 'dashboard.html',
controller: 'employeeInfoCtrl'
});
$stateProvider.state('dashboard.home',{
url:'',
templateUrl: DASHBOARD_ROOT +'/Home.html'
});
$stateProvider.state('dashboard.about',{
url:'/about',
templateUrl: DASHBOARD_ROOT +'/about.html'
});
$stateProvider.state('dashboard.employeeinfo',{
url:'/employeeinfo',
templateUrl:DASHBOARD_ROOT+'/employeeinfo.html'
});
In node : you have to add path GET#test
myApp.get('/test',function(req,resp){
resp.render('index.html');
})
you can achieve that by targeting your client build directory with
app.use(express.static('dist')) //dist is where your js is bundled
then redirect all the requests using wildcard (*) to your index.html file
app.get('*', (req, res) => res.sendFile('index.html')));

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');
});

Navigating to url directly after removing hashbangs not working

I am using angular for my app
I wanted to remove the # from the url so i added the below lines as suggested in SO answer
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
In the index.html I also added the below code as suggested here
<head>
<base href="/">
</head>
It all works fine when I navigate to pages from the home, but when i copy the url and open it in new tab, it throws 404 error
Example
When I launch the app, it's opening http://localhost:portno/home.
When I refresh the page, I'm getting a 404 error.
What other configuration should i make?
My code structure is as below
.state('tab.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/tab-home.html',
controller: 'templeHome'
}
}
})
.state('tab.list', {
url: '/list',
views: {
'tab-home': {
templateUrl: 'templates/list.html',
controller: 'templeList'
}
}
})
You need to add a route on your server that will redirect you to the entrypoint of your front (i.e: index.html).
For example, if you were redirected from your home to http://localhost:portno/foo/bar, you'll need a route to match the /foo/bar one that will redirect you to your index.html.
It migth look like this (note that this is an example code of my own written for Hapi):
server.route([
{
method: 'GET',
path: '/foo/bar',
handler: function(request, reply) {
reply.file('./public/index.html');
}
}
...

Can't navigate directly to URL Angular UI Router

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');
});

html5mode wrong mime type

I've got my redirect working correctly, the only problem is now all my style sheets are being served as text/html because it's being piped through core.index It only gives me the error for style sheets too not JS. How do I resolve this?
Error:
Resource interpreted as Stylesheet but transferred with MIME type text/html:
application.js
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider',
function($locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$locationProvider.hashPrefix('!');
}
])
express.js
app.use(express.static(path.resolve('./public')));
// Globbing routing files
config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
require(path.resolve(routePath))(app);
});
var core = require('../app/controllers/core.server.controller.js');
app.get('/*', core.index);
core.server.controller.js
exports.index = function(req, res) {
res.render('index', {
user: req.user || null,
request: req
});
};
core.client.routes.js
// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// Redirect to home view when route not found
$urlRouterProvider.otherwise('/404');
$stateProvider
.state('admin', {
url: '/admin',
templateUrl: 'modules/core/views/home.client.admin.view.html',
});
}
]);
That would not be the correct way to serve static content - images, CSS and javascript files that run on the browser.
Take a look at this article
Basically, assuming that your directory structure is as follows:
-- public
|-- css
|-- img
`-- js
where public is the folder that contains all the sub folders for hosting stylesheets, images etc.
Then, in your nodejs code, where you have the var app = express() code, have the following code after it:
app.use(express.static('public'));
Thus, when the browser encounters a stylesheet declaration such as:
<link rel="stylesheet" href="css/style.css/>
it will make a request to /css/style.css and your express server will then correctly serve the stylesheet.
Have the code app.get("/*", core.index) at the end of all the above code to ensure that it is the last option that the server tries when attempting to match a request path to a request handler.

Resources