When you have certain javascript functions that you would like to run on the server side whether it be for performance or to hide proprietary code, how would you send and receive the data with AJAX requests when your HTML file accesses external CSS and Javascript files?
For example, what would be the correct way of moving the function "secret_calculation" into index.js (the node.js file)
index.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('app.html', function (err, data) {
if (err)
{
console.log(err);
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
fs.readFile('app.css', function (err, data) {
if (err)
{
console.log(err);
}
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data);
res.end();
});
fs.readFile('app.js', function (err, data){
if (err)
{
console.log(err);
}
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.write(data);
res.end();
});
}).listen(8000);
app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="app.css">
</head>
<body>
<input id="in_put" type="text" maxlength="3" size="5" oninput="this.value = this.value.replace(/[^0-9]/g, '');" >
<span> x 5 = </span><span id="answer"></span>
<br><br>
<input type="button" id="button1" value="Calculate">
<script src="app.js"></script>
</body>
</html>
app.css
span
{
color: red;
}
app.js
document.getElementById("button1").addEventListener("click", get_input);
function get_input()
{
user_input = parseInt(document.getElementById("in_put").value);
user_input = user_input || 0;
ans = document.getElementById("answer");
ans.innerHTML = secret_calculation(user_input);
}
function secret_calculation(num)
{
var result = num * 5;
return result;
}
I've found a good example with node.js AJAX requests here, however the article doesn't use external css and javascript files