Angular And Node routing - angularjs

I am using Node for back end Angular for front end but what will happen if will declare same route for front end and backend. I haven't tried it yet.
E.g: If I am building a TODO app and if I have /todos back end service and I am rendering todos view with same route using angular.

AngularJS is processing the route after the # by default. So nothing will happen if you don't change that.
Otherwise, the backend route will be called.

Angular is client side browser framework. Your app defaults to slash(/) which points to your index.html. Your routes prefixed with hash(#) which prevents browser to make requests to server.
Angular defaults to client side & use its own routing mechanism. Express provides server side RESTful routes which behaves like an REST Api for your angular app.
In case if you want to use HTML5 Pushstate API(removes hash(/)) from default angular routing mechanism, the only thing which separates angular routes and express/server routes, You just need to structure your app like below.
express()
.use('/api', backend) // backend is express app
.use('/', www) // www is public/static files
.all('/*', function (req, res, next) {
"use strict";
// Just send the index.html for other files to support HTML5Mode
res.sendfile('./app/index.html', {root: __dirname});
})
.listen(process.env.PORT || 8888, function () {
debug('Express dev server listening on port ');
});
Your express/server routes lies after /api part, and other routes(obviously your angular routes) will return index.html(html snapshot).
Above mechanism is mostly preferable for MEAN web apps.

Angular provides its own routes after # like myhost.io/angular/#/someroute while node provides ordinar routes like myhost.io/some/other/route witch makes almost impossible to fail!
NOTE:
But you must be careful with setting routes, because if you have static files (like angular client), your routes with same path won't work using express or connect.

Related

How to route for a react-router app using express?

So I have a backend running in expressjs and I have multiple routes on it. Now I just followed this tutorial to set up a RESTful api on express. Now I want to switch to full react on the frontend, so that I will have an api running in the backend to get things from the database and am thinking using fetch from react to get that data. I saw many people say that is the best way to do it. But now there is an issue, I am not sure how to route for this. I have react-router setup so I am assuming I would use that. But how can I serve these files to the client side? How can I make sure every route except /api routes just serve my js files? Like I have a built folder already with an index.html and main<hash>.js. I am running them easily but how can I intergrate them with express? I was not able to find any answers to this. How can I route for a reactjs app to be served using expressjs? and also I saw a tutorial telling me to use a * route but that means even my api routes will only point to that.
There are three ways basically to render an application.
One is Server Side Rendering, the other one is Client Side rendering and the third one is Isomorphic rendering.
So if you are defining your routes in Nodejs and navigating the application through those routes than it will be entirely server side rendering.
I saw a tutorial telling me to use a * route but that means even my
api routes will only point to that. ? How can I make sure every route
except /api routes just serve my js files?
Regarding this what you can do is
server.get('/api', (req, res, next) => {
//You can handle the request here
})
server.get('*', (req, res, next) => {
//You can handle the request here
})
You can define your route in this order.So by this way any call to the '/api' will be handled by the first route and all the other request will be handled by the second route.
Now I want to switch to full react on the frontend, so that I will
have an api running in the backend to get things from the database and
am thinking using fetch from react to get that data
Here you dont need this.It will be an client side rendering completely
server.get('*', (req, res, next) => {
//You can handle the request here
})
For this you can create an react app from scratch or use some boilerplate (https://github.com/facebookincubator/create-react-app).
There you can define all the routing and simply call the url http://localhost/api/xxxx and get the data and you can use this data in the frontend.In this case there will be a Nodejs Server which will be serving the frontend and the expressjs server will he hosting the 'api' service to get data from.
I have react-router setup so I am assuming I would use that. But how
can I serve these files to the client side?`
How can I route for a reactjs app to be served using expressjs?
The Reactjs app when compiled is a combination of static files comprising mainly of html, css, javascript. If you want your app to be served by your express.js server then you need to use isomorphic rendering. It is by far the best approach for rendering application as it is good for SEO and initial fast page load. It comes at the cost of a complicated setup. In this case, whenever the page refreshes or the first request comes, express will serve the first page (index.html) and index.html will contain the required static(bundled) js and css files for client side rendering. The first rendering will be done by the express server and the subsequent rendering will be done by browser itself.

How can Laravel ignore everything except certain prefix?

I have my angular app running off of my laravel route /
I have everything else under /api.
I want to be able to enable html5 mode in angular and maintain SPA like routing, but when I do, laravel catches the route.
So how can I get laravel router to ignore everything except api and the initial route?
using laravel 5.2
I think you can do the following:
// Catch any routes except 'api'
Route::any('{all}', 'InitController#index')->where('all','^((?!api).)*?');
You will need to have a catch-all route to render index view on every request - then let Angular handle routing. Remember, you will also need to create 404 pages etc within Angular app.
// API routes here
// Catch-all route to point everything to index page
Route::get('{something}', function() {
return view('index');
});
With regards to the API routes, you need to place these above your catch-all route so that they return an API response.
Angular Routing
Are you using Angular 1 or 2? What angular router are you using? e.g. with Angular1 using $location you add false as 2nd parameter to path:
$location.path('/some-path/', false);

Using both Angular routeProvider and Express routes

I'm trying to make angular's routeProvider to manage all the routes of my app. I define my routes accordingly in the app.js file of angular (client side):
(function(){
var app = angular.module("Crowdsourcing", ["ngRoute"]);
app.config(function($routeProvider){
$routeProvider
.when("/single/:street/:buildingNumber/:apartmentNumber", {
templateUrl: "/views/single.html'",
controller: "ListingCtrl"
})
.otherwise({redirectTo:"/"});
});
}());
However, when writing a URL (e.g. /single) on the browser that request is tried to be handled by my backend express/node api. Thus, it is not found because the backend routes are for example /api/foo. How can I make sure Angular's routeProvider always manages my requests?
And more important what is the basic flow of the application? When Client writing a URL how does the application knows whether the url is handled by express js or by routeProvider ?
Generally you distinguish URLs which are handled by the angular app from the express URLs by using a # sign between hostname and page URL.
For example:
If you want to request an URL from the backend you would call:
http://host.com/api/foo/
Instead if you want to request an URL from the angular app you would call: http://host.com/#/single
So if you want to call the angular app URL you have add the # sign.
This is a very important fact you need to keep in mind when working with single page applications.
Update:
Have a look at this seed project: https://github.com/btford/angular-express-seed
It uses the a similar technology stack as your project. This should make it more clear for you.
I have faced the same issue few days ago. The problem is, even when you make a server call for data it redirects it to client side routing and searches in $routeProvider.
You need to make sure you add something like below code in your server.js.
It means when ever there is a call starting with /api then it will redirect it to the routes in server side instead of client side routing.
var api = express.Router();
require('./app/routes')(api);
app.use('/api', api);
In your factory when we make a call as below this will go to server side routes.js rather than client side.
$resource('/api/adduser')

How does Angular and Express routing work together in a mean.js app?

I'm struggling about Angular and Express Routing (by the way, i'm somehow new to Express), i've been handling routes with Angular — with ui-router — but now that i'm starting to build a MEAN.js Application i notice that i can handle server-side routing and client-side routing... and that's what makes me get confused, here are some of my questions:
How are they different?
If i switch to Express routing will i still have a SPA?
Can i use both at same time? How? Is it good practice? Does it has any benefit?
When should i use only one of them?
How will i handle route parameters?
etc...
If someone can explain with detail these questions, and other extra things people need to know i'll be totally thankful.
Also, something that i want to know is: Do i only have to setup server things in Express or do i need to code in Node?
Routing in Express is sightly different then what it is in angular
In express
Routing refers to the definition of end points (URIs) to an
application and how it responds to client requests.
So if you are doing the routing using angularjs then you do not need to set the route for your html template using express.
you simply use express in a way to create your RESTAPI and then consume those API using angularjs $http or $resource
Summary:
Routing in Angular supports the idea behind a SPA. Ultimately you want to handle UI based route changes (i.e. no server call/logic needed) via Angular. Any route change that hits the backend, and ultimately requires server logic, should use Express routing.
Example
This is express routing to create rest API.
app = express();
app.get('/dowork',function(res,req){
console.log(req.params.msg);
/... code to do your work .../
});
now in angularjs call do work
$http.get('http://localhost:8080/dowork',{"msg":"hi"}).success(function(data){
console.log(data);
});
Just two cents here. Other expert should correct me and explain further :
Routing at frontend usually means routing management in url after #.
This is because anything after # is ignored by browser. So this is utilized by angular to make on the fly ajax calls and fetch resources depending on route path after #.
What express handles is url before #. This is used to make actual request from browser to server.
How are they different : answered
If i switch to Express routing will i still have a SPA :
You can always have SPA if you manage urls manually at front end side while making ajax calls to populate your single page. managing urls at front end should be with intention of readability.
Can i use both at same time? How? :
Everyone uses both. A SPA also uses both. Usually authentication based thing is handled by express routing while authorization and other routing based interaction like requesting for resources and others, front end routing is used. Even if you use front end routing, for ajax request behind the scene, you are still relying on express's routing.
Is it good practice? Does it has any benefit? :
Using express's routing for authentication and providing resources AND using angular routing for front end to keep SPA in action is always a good practice.
When should i use only one of them? : answered
How will i handle route parameters? :
There are parameters handling both for front end side using route params ( if using ng-route) and at the back end using slug, bodyparser and others.
You need to spare some time learning those.
Can we use both
of-course you can use both. Depending on your application requirement, what portion of your app need to be spa for better user experience and what portion views need to be render by your express app.
If i switch to Express routing will i still have a SPA?
if a particular routing is not handled by angular and you want to generate a view by express app you can do that. if you want to develop a complete spa then you need to develop a api (http end points) in you express app to respond to AJAX requests of your angular app. Angular routing is all bout clint side routing that is used to generate template and fetch data from server (in your case express) and render a view. Over all your angular routing calls to your express routing to fetch json data or any template to give the impression of a spa
example
in express we have
app.get("/", function (req, res) {
res.render("home");
});
you home page must include all the angular script files to initialize the angular app
in clint side code you can have
var app = angular.module("myApp", ["ui.router"])
.config(function ($stateProvider, ) {
$stateProvider.state("home", {
url: "/"
})
.state("manas", {
url: "/manas",
templateUrl: "/templates/manas.html"
// when the state or url is manas its fetch the static manas.html from server and inject that to ui view
})
// i am using angular UI router here
Can i use both at same time? How? Is it good practice? Does it has any benefit?
Ya we can use both at same time. It depends on your application logic their is no harm or benefit of using both.
When should i use only one of them?
Go with express routing only if you are more concerned about search engine optimization. Because SPA are not by-default search engine friendly you need to take some extra action to make it search engine friendly.
How will i handle route parameters?
it depends on what angular routing you are using. I mean vanilla angular routing or UI routing. But the concept is same for both
passing parameters
For passing parameters to server with UI routing go through
https://github.com/angular-ui/ui-router/wiki/URL-Routing#url-parameters
for UI routing follow this link
https://github.com/angular-ui/ui-router/wiki
if you app is not more complex you don't care about nested views child views etc
my suggetion go with angular plain routing.
No doubt UI router gives more advance routing concepts but learning curve is steep as well. if you app is simple in nature go with angular routing

Isomorphic Javascript Routes with React-Route vs REST API Routes

I have been studying react/flux/react-router and how pre-rendering virtual DOM in server happens. Calling Router.run() and renderToString in the server will take care of pre-rendering the page in the server and lazily loading and downloading the rest of .js files to the client. React-router deals with UI URLs in any scenario (either client or server). This is not necessarily the same as REST API URLs of the server.
What is the best practice to add routes functionality If I want to use the backend for a native app with REST features as well. should I have a complete set of routes definitions for express.js and re-define all the routes in react-routes as well?
React routes are not necessarily similar to express routes (can have more or less route patterns). So replicating route definitions seem inevitable. Is that correct? even this example seems to be doing the same thing.
I was hoping to find a way to reuse routes definition or something more DRY.
You don't want to duplicate routes on a client and server. See flux examples from Yahoo: https://github.com/yahoo/flux-examples/tree/master/react-router
Then, just specify API request before the react router on the server. E.g.:
var express = require('express');
var server = express();
// Static files
server.use('/assets', express.static('src/assets'));
server.use('/build', express.static('build'));
// Declare API handling:
require('apiRouting')(server);
// Decalre react-router handling
require('./routing.jsx')(server);
// In the apiRouting.js:
module.exports = function (server) {
server.get('/api/methodA', function (req, res) {
// body...
});
server.get('/api/methodB', function (req, res) {
// body...
});
};
Also, there's a library that makes it so you can build your APIs in an isomorphic fashion, and re-use it in the client and server without bloating or breaking the bundle. This is what we're currently using in a big single-page application.
It's called Isomorphine, and you can find it here: https://github.com/d-oliveros/isomorphine.
Disclaimer: I'm the author of this library.

Resources