Ryan Ryan - 1 month ago 6
AngularJS Question

Using express.js to execute a function after receiving an http request?

So I have an angular controller that successfully makes an http request after a button is pressed. I have a node.js server running which gets the request and then sends back

YOU HAVE SUCCEEDED! HTTP REQUEST RECEIVED!
. I want to execute a function when the request is received, but the function lives in a file inside a folder which is in
./Source/Server/test.js
.

How do I tell my server.js file to send the command to run the function???

server.js:

var express = require('express');
var app = express();
var fs = require('fs');
app.use(express.static(__dirname + '/Source/Client/Templates'));
app.use(express.static(__dirname + '/'));
app.get('/', function (req, res) {
res.sendFile('/Source/Client/Templates/Home.html', {root: __dirname });
});
app.get('/ThisIsATest', function (req, res) {
res.send('YOU HAVE SUCCEEDED! HTTP REQUEST RECEIVED!')
})
app.listen(3000);
console.log("running at port 3000");


test.js:

var run = require('./quickstart.js');
run.runQuickstart();


Controller:

angular.module('DaycareApp').controller('WaitingListController', ['$scope', '$http', function($scope, $http){
$scope.test = function() {
$http.get('/ThisIsATest')
.then(function(response) {
alert(response.data);
});
};
}]);

Answer

In test.js you can export your module like this

var run = require('./quickstart.js');

function mySpecialFunction() {
    return run.runQuickstart();
}

module.exports = {
    mySpecialFunction: mySpecialFunction
};

Now in your server.js or wherever your controller is you can call the function by inluding test.js in your module using require.

var test = require('./test.js');

app.get('/ThisIsATest', function (req, res) {
  res.send(test.mySpecialFunction());
});