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

Remove Apache2 from linux server

Here we are,

I’m leaving Apache for Nginx which is a faster asynchronous http server.
If you need more informations about it, please go here http://www.wikivs.com/wiki/Apache_vs_nginx.

So, to start with a clean base, I’ve had to first remove apache from my server, this is how to deal with it.

//Stop apache server
sudo service apache2 stop 

//Uninstall Apache2 and its dependent packages
sudo apt-get purge apache2 apache2-utils apache2.2-bin apache2-common

//By precaution
apt-get purge apache2

//remove any other dependencies that were installed with Apache2, but are no longer used by any other package
sudo apt-get autoremove

//Delete apache2 directory manually
sudo rm -rf /etc/apache2

Thank you for reading.

Remove Apache2 from linux server