AngularJS and Express Routing issue - angularjs

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?

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

Sending all routes or paths to angular

In my node js app.js I want that whatever the url is it goes to my angular/html page i.e. begin.html, app.js resides in server folder and begin.html is in client folder of my project. It's like :-
-Project
----Server
---------app.js
----Client
---------begin.html
What should I type in app.js so that all the urls go to begin.html where i am using Angular routing?? I think its something like..
var begin=require('../Client/begin.html);
app.use('*',begin);
If you are going to just have all routes go back to that HTML page, then you could just use a web server like Nginx serve that directory statically.
It looks like you are using Express, but that is just a guess. If you want to make HTTP requests from your Angular side to your Node.js side then you will probably want the default response to return your HTML, but still be able to allow requests through. I would look at using the static method from express to expose a static directory while still allowing you to build other routes (i.e. api routes).
It might look something like this:
// Already created express app above
/*
This will default to using index.html from
your Client directory and serve any other resources
in that directory.
*/
app.use(express.static('../Client'));
// Any other routes
app.listen(3000); // Or whatever your port is
Or you could also implement it using the 404 error handler style and return your default file:
/*
This comes after all of your other
route and middleware declarations and
before the .listen() call
*/
app.use(function(req, res, next) {
res.sendFile(path.join(__dirname + '/../begin.html'));
});

How to send an AngularJS file with ExpressJS?

I'm new with ExpressJS, I have a small example using EJS, but I want use AngularJS for manipulating the DOM. Both technologies offer me DOM manipulation, so why some people use it together? I don't understand.
I have no idea how to render HTML files. What is the correct way to use AngularJS with ExpressJS?
res.render('index.html');
As far as I know EJS is really for templating, none of the embedded js is executed on the client.
Personally I have found some cases where it is handy to use a templating language with AngularJS or any client side framework. For example, sometimes it is nice to be able to interpolate some csurf tokens, or session data required by the client app into your html on the server. Other times it is not necessary.
As for rendering html, use the express.static middleware. It comes with Express, you pass a file path, and it returns a handler that will serve the contents of a given directory. You could put express.static anywhere in your middleware chain, but I usually put it at the top to avoid naming issues. Read the documentation for more information.
Consider the following:
var express = require('express')
var app = express();
// Asssuming we have a directory
// `public` in the root of the application
app.use('/', express.static(__dirname + '/public'));
// now you're serving all the files in public directory off the root path
// Add middlewares and routes...
For a really simple app you could you use the fs module, and stream the contents of a file to the response. The following is naive example of how you could do this, in production you would want to listen for error events and implement some cache control.
app.get('/', function(req, res) {
res.set('Content-Type', 'text/html');
fs.createReadStream('./index.html').pipe(res);
});
Please use this :to render first time
and for more information please go her http://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})

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

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

Resources