使用 node.js 和 AJAX 请求将 Javascript 函数移动到后端
Moving Javascript function to backend with node.js and AJAX requests
当您想要在服务器端 运行 某些 javascript 功能时,无论是为了提高性能还是为了隐藏专有代码,您将如何使用 AJAX 当您的 HTML 文件访问外部 CSS 和 Javascript 文件时发出请求?
例如,将函数“secret_calculation”移动到 index.js(node.js 文件)的正确方法是什么
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;
}
我找到了 node.js AJAX 请求 here 的一个很好的例子,但是这篇文章没有使用外部 css 和 javascript 文件
使用 express,您可以使用 GET
动词绑定路由并在客户端获得响应。
例如:
index.js
const express = require('express');
const app = express();
app.get('/your-route-here', (req, res) => {
res.send({response: req.query.num * 5});
});
app.js
let calculatedSecret;
fetch('/your-route-here')
.then(({data}) => {
calculatedSecret = data.response;
});
这样做的一种方法是 运行 第二个 http 服务器将这些功能作为服务提供(类似于休息 API)。
为了简单起见,我将使用 express(将其简单地包装为 HTTP 服务器):
var http = require('http');
var fs = require('fs');
var express = require('express');
var bodyParser from 'body-parser';
// this is server code and won't get to the client if not required
function secret_calculation(num) {
var result = num * 5;
return result;
}
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);
var apiApp = express();
// to be able to use request.body for complex parameters
apiApp.use(bodyParser.json());
apiApp.use(function (req, res, next) {
// to restrict api calls to the ones coming from your website
res.append('Access-Control-Allow-Origin', <url of your domain, with port>);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//the list of routes your API will respond to, it is better to move this code in another file as it can be huge
apiApp.get('/secret_calculation/:number', function(req, res) {
var num = parseInt(req.params.number, 10);
var result = secret_calculation(num);
res.send(JSON.stringify(result));
});
// define as much routes as you want like the model above, using apiApp.post if you want to post data and retrieve it with req.body...etc
// run the API server like your http server above
apiApp.listen(8001, function (err) {
if (err) {
return console.error(err);
}
console.info(`apiApp listening at ${<url to your domain, without port>}:${8001}`);
});
然后在您的应用程序中,您将能够通过调用(使用 fetch,但任何其他 ajax 库都可以)从 secret_calculation 检索值:
function get_input() {
const init = {
'GET', // or POST if you want to POST data
headers: { 'Content-Type': 'application/json', 'Accept-Encoding': 'identity' },
cache: 'default',
// body: data && JSON.stringify(data), if you want to POST data through request body
};
var user_input = parseInt(document.getElementById("in_put").value);
user_input = user_input || 0;
fetch('/secret_calculation/' + user_input, init)
.then( function(response) {
var ans = document.getElementById("answer");
ans.innerHTML = response;
})
.catch ( function(error) {
console.log('something bad happened:', error);
});
}
Simple tutorial to create a REST API in 5 minutes with express (similar to the above
当您想要在服务器端 运行 某些 javascript 功能时,无论是为了提高性能还是为了隐藏专有代码,您将如何使用 AJAX 当您的 HTML 文件访问外部 CSS 和 Javascript 文件时发出请求?
例如,将函数“secret_calculation”移动到 index.js(node.js 文件)的正确方法是什么
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;
}
我找到了 node.js AJAX 请求 here 的一个很好的例子,但是这篇文章没有使用外部 css 和 javascript 文件
使用 express,您可以使用 GET
动词绑定路由并在客户端获得响应。
例如:
index.js
const express = require('express');
const app = express();
app.get('/your-route-here', (req, res) => {
res.send({response: req.query.num * 5});
});
app.js
let calculatedSecret;
fetch('/your-route-here')
.then(({data}) => {
calculatedSecret = data.response;
});
这样做的一种方法是 运行 第二个 http 服务器将这些功能作为服务提供(类似于休息 API)。
为了简单起见,我将使用 express(将其简单地包装为 HTTP 服务器):
var http = require('http');
var fs = require('fs');
var express = require('express');
var bodyParser from 'body-parser';
// this is server code and won't get to the client if not required
function secret_calculation(num) {
var result = num * 5;
return result;
}
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);
var apiApp = express();
// to be able to use request.body for complex parameters
apiApp.use(bodyParser.json());
apiApp.use(function (req, res, next) {
// to restrict api calls to the ones coming from your website
res.append('Access-Control-Allow-Origin', <url of your domain, with port>);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//the list of routes your API will respond to, it is better to move this code in another file as it can be huge
apiApp.get('/secret_calculation/:number', function(req, res) {
var num = parseInt(req.params.number, 10);
var result = secret_calculation(num);
res.send(JSON.stringify(result));
});
// define as much routes as you want like the model above, using apiApp.post if you want to post data and retrieve it with req.body...etc
// run the API server like your http server above
apiApp.listen(8001, function (err) {
if (err) {
return console.error(err);
}
console.info(`apiApp listening at ${<url to your domain, without port>}:${8001}`);
});
然后在您的应用程序中,您将能够通过调用(使用 fetch,但任何其他 ajax 库都可以)从 secret_calculation 检索值:
function get_input() {
const init = {
'GET', // or POST if you want to POST data
headers: { 'Content-Type': 'application/json', 'Accept-Encoding': 'identity' },
cache: 'default',
// body: data && JSON.stringify(data), if you want to POST data through request body
};
var user_input = parseInt(document.getElementById("in_put").value);
user_input = user_input || 0;
fetch('/secret_calculation/' + user_input, init)
.then( function(response) {
var ans = document.getElementById("answer");
ans.innerHTML = response;
})
.catch ( function(error) {
console.log('something bad happened:', error);
});
}
Simple tutorial to create a REST API in 5 minutes with express (similar to the above