Call php scripts from AngularJs running under NodeJs with express

Hi everyone,

Last night I’ve broken my head trying to run a php script from an Angular application running under Nodejs with the excellent “express” http server.

First, let’s go back to the basics, what is NodeJs?
Node.js® is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications” Source: (http://nodejs.org/).

NodeJs is not directly a server, but a platform that can implements a lot of modules, like an http server.
For my project I’m using expressJs web application framework. More documentation about expressJs here: http://nodejs.org/

With expressJs, you can use an http server without having to use an external software like Apache, Lighttpd or Nginx.
it will offer you the opportunity to serve static files (html, js, css…), but not dynamic files like php files.
Give it a try by calling a php file within your angular application only running under NodeJs, you will get a 404 (forbidden error).

To solve this problem, you have multiple issues:
– Try to customize a module that will enable php parsing inside NodeJs
– Use an additional php server like Apache or Nginx

For simplicity reasons, we will choose the second option, it was my case after hours of research.
So, turn on your external http server (if it’s not already the case).

Right, now you have two servers running on different ports (Apache or Nginx, or anything else on port 80, and Node on port 8080 or another).

The solution will be:
1. To call your php files on port 80 served by your php server, inside your ajax call, just like this:

$http({
    method  : 'POST',
    url     : 'http://localhost:80/process.php',
    data    : $.param($scope.formData),
    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
    console.log(data);
}).error(function(data) {
    console.log(data);
});
  1. Allow CORS within your server side application, as we’re making ajax requests
    header("Access-Control-Allow-Origin: *");
    

And voilà, the job is done.

Call php scripts from AngularJs running under NodeJs with express

Differences between JQuery and AngularJS

Firstly you have to know that AngularJS and JQuery are different javascript frameworks, so never, never mixed up AngularJS with JQuery code. If you’re a JQuery magic developer, please invest some times in AngularJS, it will change your life.

Separation of concerns

AngularJS helps you keep your concerns separate with powerful utils (controllers, directives, models and view). The view is like a plasticine formless that you remodel through directives (DOM manipulation abstraction that help you augment your view) and models (that represent your datas), that are encapsulated in a controller linked to a specific html section. Unlike JQuery, this separation of concerns help you have testable code (remember the last time you’ve seen a jQuery plugin with unit tests).

<section id="todoapp" ng-controller='todoController'>
    <header id="header">
        <h1>TODOList</h1>
        <form id="todo-form" action="#" ng-submit='addTodo()'>
            <input id="new-todo" autocomplete="off" type="text" autofocus="" ng-model='newTodo' placeholder="{{placeholder}}" />
        </form>
        </header>
    </section>

In this code, what you see as ng-x is called a directive. ng-controller means that this section of code is related to todoController controller and the input data is specified as newTodo model (ng-model). Use of directives is also called use of decorator pattern.

Bi-directional data binding

In the previous code, modification in the view will affect the controller that can also affects the view. In the following code, when the form will be submitted, the input value will equal “Loader ended” ! it is as simple as that, how do you figure that in JQuery?

var app = angular.module('todo', []);
    app.controller('todoController', function ($scope, filterFilter, $http, $location) {
        $scope.placeholder = 'Loading...';
        $scope.addTodo = function (){
            $scope.newTodo = 'Loader ended';
        };
    };

Dependency injection

One other great tool from AngularJS is dependency injection (DI). Dependency Injection can seem very awful if you’re not familiar with back-end languages like php or Java, but it will become very useful and simple, i promise.
Dependency injection means that you have one service “A” (class that does a specific job) which needs an instance of another service “B” in order to work, we then say that we inject B into A without having to worry about loading order, or file locations, or anything like that.
DI in AngularJS will take all its sense in unit testing.

Test driven development

How many JQuery plugins have you seen, used, or written, which contained test suite? Not very many because you JQuery needs iterative development and doesn’t suit SOLID principle, but AngularJS does.
In jQuery, the only way to test a plugin is to develop a separated component with a demo page to perform DOM manipulation, and then integrate it into our application. Because of that, we opt for iterative instead of test-driven development. How inconvenient!

I’ve written an exemple of unit testing with AngularJS here https://creativcoders.wordpress.com/2014/05/11/angularjs-test-driven-development-tutorial/, have a look to.

Conclusion

Remember, AngularJS is not JQuery, don’t even include JQuery above AngularJS, it will hold you back. When you come to a problem that you think easier to solve with JQuery, try to think about how to do it within the confines the AngularJS before. If you don’t know, ask for, it will save you time, believe me.

Differences between JQuery and AngularJS