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.

Advertisements
Call php scripts from AngularJs running under NodeJs with express

jsHtml5AVRecorder – Record html5 audio and video simultaneously and convert them to mp4

A few days ago, I’ve published two javascripts plugins, jsHtml5AudioRecorder and jsHtml5VideoRecorder.

Each of them allows you to record respectively, audio and video from html5 live stream.

jsHtml5AVRecorder is a wrapper of these two plugins.
It allows you to record simultaneously audio and video from live stream, and convert them to mp4 using FFMPEG.

It is really simple to understand, this is how to use it:

var jsAVRecorder = new jsHtml5AVRecorder();
jsAVRecorder.audioWrapper                    = jsAudioRecorder;      //jsHtml5AudioRecorder object with parameters - here https://github.com/edouardkombo/jsHtml5AudioRecorder
jsAVRecorder.videoWrapper                    = jsVideoRecorder;      //jsHtml5VideoRecorder object with parameters - here https://github.com/edouardkombo/jsHtml5VideoRecorder
jsAVRecorder.convertFilesTo                  = 'mp4';                //MP4 is the extension in which convert the medias
jsAVRecorder.doConversion                    = false;                 //Apply conversion
jsAVRecorder.streamConvertedResult           = false;                 //Show the result of the conversion
jsAVRecorder.deleteSeparatedFiles            = false;                 //Delete audio and video files, to only keep the single file
jsAVRecorder.mediaPath                       = '/medias/Temp/';
jsAVRecorder.phpFile                         = '/form/convertProcess.php'; //File is included inside the repository


jsAVRecorder.init();

function startRecording() {
    jsAVRecorder.startRecording();
}

/**
 * You can use "save", "saveAndDownload" or "saveAndStream", "downloadAndStream" parameters
 */
function stopRecording() {
    //For demo
    jsAVRecorder.stopRecording('stream');
    
    //In production
    //jsAVRecorder.stopRecording('saveAndStream');
}

Feel free to help improve this code and leads it at another level.

The complete code is hosted on Github: https://github.com/edouardkombo/jsHtml5AVRecorder
 
Demo is available here: https://edouardkombo.github.io/jsHtml5AVRecorder/demo
 
To download from Bower:

bower install js-html5-av-recorder
jsHtml5AVRecorder – Record html5 audio and video simultaneously and convert them to mp4

jsHtml5PhotoBooth – take snapshots from webcam stream, apply watermark, rotate and print result without prompt

Hi everyone,

This is one of my favorite plugin I’ve ever developed.

jsHtml5PhotoBooth is a powerful native javascript object that helps you take snapshots from your webcam stream, and do many other actions like:
– Apply a watermark to the picture
– Rotate the picture if needed
– Print directly the taken picture, without prompt (only work on local machines, and, on windows systems actually)

This plugin is very complete. It needs some parameters you have to be familiar with, but at the end, it will be very helpful and will save you a lot of time.

This is how to configure it:

//Instantiate the object
var jsPhotoBooth = new jsHtml5PhotoBooth();

jsPhotoBooth.width                       = '640';               //Width of the canvas and video tag element
jsPhotoBooth.height                      = '480';               //Height of the canvas and video tag element

jsPhotoBooth.resultTagIdHost             = 'media';             //Div id where to store (the picture taken by the user)
jsPhotoBooth.resultTagId                 = 'myPicture';         //Id of the result picture to show to user inside the resultTagIdHost

jsPhotoBooth.videoTagIdHost              = 'media';             //Div id where to store (video and canvas html tag element)
jsPhotoBooth.videoTagId                  = 'video';             //Id of the video tag element
jsPhotoBooth.canvasTagId                 = 'canvas';            //Id of the canvas tag element

jsPhotoBooth.pictureExtension            = 'jpeg';             //Picture extension (jpeg, png, gif, bmp)
jsPhotoBooth.pictureQuality              = '1';                 //Picture quality (from 0.0 to 1)

jsPhotoBooth.captureFromCanvas           = false;               //If you want to apply live webcam effects or not, from another script

jsPhotoBooth.showStreamOnFinish          = true;                //Show the video stream after the picture has been taken
jsPhotoBooth.hideWebcamWhileSnapshot     = true;                //Hide webcam while snapshot, strongly improves performance

jsPhotoBooth.mediaPath                   = '/medias/Temp/';     //Path where to store te picture on the server
jsPhotoBooth.phpFile                     = '/form/pictureProcess.php'; //Php file that will proceed to picture saving on the server

/**
 * This only works on local machines
 */
jsPhotoBooth.printPictureOnFinish        = true;                //Works only on windows system (You can update the batch file to your needs)
jsPhotoBooth.printOptionComputerName     = 'YOUR_COMPUTER_NAME';        //Computer name to target the network
jsPhotoBooth.printOptionSharedPrinterName= 'YOUR_SHARED_PRINTER_NAME';    //Name of the shared printer inside your windows network
jsPhotoBooth.printBatchFile              = '/form/print.bat';    //Automatically generated and deleted

/**
 * Apply watermark to the picture
 */
jsPhotoBooth.watermarkImage              = '/medias/watermark.gif';  //Path where to find the watermark image

/**
 * Apply rotation to the output
 */
jsPhotoBooth.rotation                    = 0;  //Rotate the picture

And, This is how to run it:

//Start the plugin
jsPhotoBooth.init();


function startCapture() {
   jsPhotoBooth.startCapture();
   stopRecording();
}

/**
 * You can use "save", "saveAndDownload" or "saveAndStream", "downloadAndStream" parameters
 */
function stopRecording() {
    //For demo
    jsPhotoBooth.stopCapture('downloadAndStream');

    //Use this in production
    //jsPhotoBooth.stopCapture('saveAndStream');
}

The complete code is hosted on Github: https://github.com/edouardkombo/jsHtml5PhotoBooth
 
Demo is available here: https://edouardkombo.github.io/jsHtml5PhotoBooth/demo
 
To download from Bower:

bower install js-html5-photo-booth
jsHtml5PhotoBooth – take snapshots from webcam stream, apply watermark, rotate and print result without prompt

JsRoundRunner – a useful and smart javascript counter for your web applications

A javascript counter, there are many javascript, jquery opensource counters available on the web, but this one, jsRoundRunner is specific, and is built in native javascript.

It allows you to:
– Count up and down
– Add text to counter view
– Change counter color at a specific time
– Format counter to HHMMSS
– Trigger a function at the end of the counter

Want to know how to use it? It’s simple:

//Instantiate the object
var runner = new jsRoundRunner();

//Set parameters
runner.startsAt                 = 0;
runner.endsAt                   = 15;
runner.allowMinutesAndSeconds   = false;

if (runner.startsAt < runner.endsAt) {
    runner.addToView            = '/' + runner.endsAt + 's'; //Additional text to add to the counter
    runner.baseColor            = '#000'; //Base color of the timer
    runner.changeColorAt        = 10; //Time in seconds from which counter must change color
    runner.changeColorColor     = '#FF0000'; //Color to adapt to counter after color changement 
}

runner.counterTagId             = 'counter'; //Div id where to show the counter
runner.callBack                 = stopTimer; //Function to call when jsRoundRunner stops 
runner.start();

function stopTimer() {
    alert('Hello world!');
}

The complete code is hosted on Github: https://github.com/edouardkombo/jsRoundRunner
 
Demo is available here: https://edouardkombo.github.io/jsRoundRunner/demo
 
To download from Bower:

bower install js-round-runner
JsRoundRunner – a useful and smart javascript counter for your web applications

jsApplicationTimer – a smart javascript timer for web applications

Maybe you want to develop a web application that needs to restart or do any action if user doesn’t interacts with your script during a few time.

jsApplicationTimer is the ideal solution for you.
It helps you to simply trigger a function if user hasn’t interacted with a selector you specified, in an interval of time you have specified.

It is so simple. This is how it works:

//Instantiate the object
var applicationTimer = new jsApplicationTimer();

//Set parameters
applicationTimer.callBackMethod = stopTimer;
applicationTimer.timer  = 5; //Time in seconds
applicationTimer.start();

//Callback method
function stopTimer() {
    alert('Hello world!');
}

The complete code is hosted on Github: https://github.com/edouardkombo/jsApplicationTimer
 
Demo is available here: https://edouardkombo.github.io/jsApplicationTimer/demo
 
To download from Bower:

bower install js-application-timer
jsApplicationTimer – a smart javascript timer for web applications

jsHtml5VideoRecorder – Record video stream in html5 with automatic fps

Another day, another tutorial.
Today, we will see how we can record live video from webcam in html5.

You can see many plugins on the web, but what they don’t tell you is that, the speed of your record will depend on your cpu power and your webcam model.
So, in fast modern machines with high quality webcal, your fps will be different than olders one.

To solve this problem, We will calculate the appropriate fps record, and delete frames we don’t need, if it’s the case.
To record html5 video, you’ll need the Whammy library. Whammy is fast webm encoder, you can download it here: https://github.com/antimatter15/whammy.

Also, actually, only Chrome is able to proceed to live html5 video record.
Everything is ok? So, let’s go!

First, we must check that navigator.getUserMedia is supported by our browser.

if (!navigator.getUserMedia) {
    navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
}
window.URL  = window.URL || window.webkitURL;
this.url    = window.URL;        
        
window.onload = this.onLoad();

Now, we can initiate the navigator.getUserMedia api, with audio config to true, and a stream function.

navigator.getUserMedia({ 
    video: true
}, this.startUserMedia.bind(this), function(e) {
    console.log('No live video stream: ' + e);
    alert("Webcam not enabled or no live video stream");
});

For recording a video, we first have to save the stream in a variable and load it in a video tag for live stream

this.mediaStream = stream;

//We will see this method later        
this.resetTags();

Let’s develop the resetTags method. It’s only a method that allows us to create (video and canvas) tags if needed

//Create video and canvas tag if not exists
this.createTag('video', this.videoTagId);
this.createTag('canvas', this.canvasTagId);

Why? If you don’t have html5 video or canvas tag into your document, this object can create them for you.
Here is the createTag method

var myTag   = document.getElementById(tagId);
       
if (myTag === null) {
            
    myTag = document.createElement(tag);
            
    if (tag === 'canvas') {
        myTag.width             = this.width;
        myTag.height            = this.height;
        myTag.id                = tagId;
        myTag.style.position    = 'absolute';
        myTag.style.visibility  = 'hidden';
        this.ctx                = myTag.getContext('2d');
        this.canvasTag          = this.ctx.canvas;
            
    } else if (tag === 'video') {    
        myTag.setAttribute('autoplay','true');
        myTag.width             = this.width;
        myTag.height            = this.height;
        myTag.id                = tagId;
        if (this.mediaStream !== '') {
            myTag.src = window.URL.createObjectURL(this.mediaStream);
        }
        this.videoTag   = myTag;
    }
            
    document.getElementById(this.videoTagIdHost).appendChild(myTag);    
}

Ok, right, that’s huge work, let’s have fun now by starting the record

//Remove result video tag and recreate it to empty cache
var videoElement = document.getElementById(this.resultTagId);   
if (videoElement) {
    videoElement.remove();
}
        
this.resetTags();
       
if (this.hideWebcamWhileRecording) {
    //Hide video stream while recording for performance
    this.showHideStream('hide');
}

this.hasStopped = false;
		
this.startTime   = Date.now();

this.frames      = []; // clear existing frames;
console.log('Recording video...');

this.rafId = requestAnimationFrame(this.drawVideoFrame_.bind(this));

return true; 

Notice, we have here a drawVideoFrame method. This method save each frame from canvas in an array, like this:

this.ctx.drawImage(this.videoTag, 0, 0, this.videoTag.width, this.videoTag.height);
var url = this.canvasTag.toDataURL('image/webp', 1);
this.frames.push(url);

this.rafId   = requestAnimationFrame(this.drawVideoFrame_.bind(this));

We don’t forget the showhide method, that will simplify our actions

if (status === 'show') {
    this.videoTag.style.visibility  = 'visible';
    this.videoTag.style.display     = 'block';            
} else if (status === 'hide') {
    this.videoTag.style.visibility  = 'hidden';
    this.videoTag.style.display     = 'none';           
}

So, what happens whe we decide to stop the video?
Naturally we calculate the real recorded time, that will be divided by the number of frames recorded, so we have the real video fps.
If the record was equal to max record time specified, we estimate the number of frames that will be captured.
If we have much frames than expected, we delete the extra frames, and send the other frames to Whammy for encoding.
And, we can stream, download and save the video on the server.

this.endTime = Date.now();   
        
this.hasStopped = true; 
        
cancelAnimationFrame(this.rafId);

//Recorded time
var recordedTime = (this.endTime - this.startTime)/1000;

console.log('Captured frames: ' + this.frames.length + ' => ' + recordedTime + 's video');

//We consider that the normal gap between Max recording time and real user recording time is 1s
//When the gap is greater than 1s, we auto-check the fps to synchronize the medias
var recordingGap        = this.maxRecordTime - recordedTime;

//Detect fps
var fps                 = (this.frames.length / recordedTime).toFixed(1); 
var encodingRatio       = fps; 

//Expected frames is the number of frames expected depending on the max record time
var expectedFrames      = (recordingGap <= 1) ? encodingRatio * this.maxRecordTime : encodingRatio * recordedTime ;
var unexpectedFrames    = this.frames.length - expectedFrames; 

//If there are more frames than expected, remove unexpected frames
if (unexpectedFrames > 0) {
    var i=0;
    for (i = 0; i <= unexpectedFrames; i++) { 
       this.frames.pop();
    }
} else {
    encodingRatio   = ((this.frames.length * fps) / expectedFrames).toFixed(3);
}                

console.log('Stop Recording video!'); 
console.log('My FPS => '+ fps);
console.log(encodingRatio);             

var webmBlob = this.whammy.fromImageArray(this.frames, encodingRatio);
console.log(webmBlob);
        
if (method === 'save') {
    this.save(webmBlob, false);
            
} else if (method === 'download') {
    this.download(webmBlob, false);
            
} else if (method === 'stream') {
    this.stream(webmBlob);

} else if (method === 'saveAndDownload') {
    this.save(webmBlob, false);
    this.download(webmBlob, false);
                      
} else if (method === 'saveAndStream') {
    this.save(webmBlob, true);
            
} else if (method === 'downloadAndStream') {
    this.download(webmBlob, true);
            
} else {
    this.save(webmBlob, false);
}

//If specified, we show original video stream        
if (this.showStreamOnFinish) {
    this.showHideStream('show');
}
        
//Empty frames for next video capture
this.frames = [];
               
return true;

Right, now we can specify our “download”, “save” and “stream” methods.

Save method

var datas   = 'path='+this.mediaPath+'&format='+this.videoFormat;                  

var client = new XMLHttpRequest();
client.onreadystatechange = function() 
{
    if (client.readyState === 4 && client.status === 200) 
    {
        console.log(client.response);

        //Get the video link, so we can use it later in other scripts
        this.videoLink = client.response;

        if (stream) {
            this.stream(blob);
        }
    }
}.bind(this);                    
client.open("post", this.phpFile+'?'+datas, true);
client.setRequestHeader("X-Requested-With", "XMLHttpRequest");
client.setRequestHeader("cache-Control", "no-store, no-cache, must-revalidate");
client.setRequestHeader("cache-Control", "post-check=0, pre-check=0");
client.setRequestHeader("cache-Control", "max-age=0");
client.setRequestHeader("Pragma", "no-cache");            
client.setRequestHeader("X-File-Name", encodeURIComponent('1'));
client.setRequestHeader("Content-Type", "application/octet-stream");
client.send(blob);

Download method

var url             = window.URL.createObjectURL(blob);
//Create a link
var hf              = document.createElement('a');

var temporaryId     = new Date().toISOString();
        
//Define link attributes
hf.href             = url;
hf.id               = temporaryId;
hf.download         = temporaryId + this.videoFormat;
hf.innerHTML        = hf.download;
hf.style.display    = 'none';
hf.style.visibility = 'hidden';
//Append the link inside html code
document.body.appendChild(hf);

//Simulate click on link to download file, and instantly delete link
document.getElementById(hf.id).click();
document.getElementById(hf.id).remove();

if (stream) {
    this.stream(blob);
}

And finally we define the stream method

var url             = window.URL.createObjectURL(blob);
        
var videoResult = document.createElement('video');
videoResult.src = url;
videoResult.setAttribute('autoplay', false);         
videoResult.setAttribute('controls', true);        
videoResult.id  = this.resultTagId;
        
document.getElementById(this.resultTagIdHost).appendChild(videoResult);
        
videoResult.pause(); 

Thank you for reading this article.
 
To download the full code, click here: https://github.com/edouardkombo/jsHtml5VideoRecorder
 
To see a live demo, it’s here: https://edouardkombo.github.io/jsHtml5VideoRecorder/demo
 
To download directly from Bower:

bower install js-html5-video-recorder
jsHtml5VideoRecorder – Record video stream in html5 with automatic fps

jsTactileScreenEvents – Manage touch events for touch screen web applications

When you develop a touch screen web application, you have many constraints like:
– Disable mousewheel
– Disable scrolling page with finger
– Disable page zoom
– Disable pinch
– Disable right click
– Disbale any touch move
– Disable page highlighting (select all or a part of the page)

Don’t worry, I’ve developped one javascript object that can do it for you all in one, “jsTactileScreenEvents”.

It is very easy to use:

//Instantiate the object
var tactileEvents = new jsTactileScreenEvents();
    
tactileEvents.disable('contextmenu');
tactileEvents.disable('zoom');
tactileEvents.disable('mousewheel');
tactileEvents.disable('touchmove');
tactileEvents.disable('highlight'); //disable text highlighting

Get the code on Github here: https://github.com/edouardkombo/jsTactileScreenEvents
See a live demo here: https://edouardkombo.github.io/jsTactileScreenEvents/demo

Or git it directly from Bower:

bower install js-tactile-screen-events

That’s right, have fun !

jsTactileScreenEvents – Manage touch events for touch screen web applications