index.html
代碼:javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>付款頁面</title>
</head>
<body>
<h1>您的帳戶餘額爲:<span id="money">_money</span></h1>
<button id="button">付款</button>
<script>
let money = document.getElementById('money');
let button = document.getElementById('button');
button.addEventListener('click', e => {
let script = document.createElement('script');
let functionName = 'lvbin' + parseInt(Math.random() * 100000, 10);
window[functionName] = function (result) {
if (result === 'success') {
money.innerText = money.innerText - 1;
}
}
script.src = '/pay?callback=' + functionName;
document.body.appendChild(script);
script.onload = e => {
e.currentTarget.remove();
delete window[functionName];
};
script.onerror = e => {
e.currentTarget.remove();
delete window[functionName];
};
});
</script>
</body>
</html>
複製代碼
server.js
代碼:html
const http = require("http");
const fs = require("fs");
const url = require("url");
const childProcess = require("child_process");
const port = process.env.PORT || 3000;
//調用http的createServer方法,它能夠建立一個網絡服務。接受請求並響應
const server = http.createServer((request, response) => {
const path = url.parse(request.url, true).pathname;
const query = url.parse(request.url, true).query;
if (path === "/") {
let string = fs.readFileSync("./index.html", "utf8");
let money = fs.readFileSync("./money");
response.setHeader("Content-Type", "text/html");
string = string.replace("_money", money);
response.write(string);
response.end();
}
if (path === "/pay") {
let money = fs.readFileSync("./money", "utf8");
let newMoney = money - 1;
fs.writeFileSync("./money", newMoney);
response.setHeader("Content-Type", "application/javascript");
response.statusCode = 200;
response.write(`${query.callback}.call(undefined,"success")`);
response.end();
} else {
response.statusCode = 400;
response.end();
}
});
//調用server對象的listen方法,設置監聽的端口號
server.listen(port);
console.log(`正常監聽,服務運行在:http://127.0.0.1:${port}`);
//自動在瀏覽器打開地址
childProcess.exec(`start http://127.0.0.1:${port}`);
複製代碼
money
文件代碼:java
100
複製代碼