JSONPの小さなケース

4804 ワード

index.htmlコード:

"en">


  "UTF-8" />
  "viewport" content="width=device-width, initial-scale=1.0" />
  "X-UA-Compatible" content="ie=edge" />
   



  

は「money」>money

<span class="hljs-built_in">let</span> money = document.getElementById(<span class="hljs-string">'money'</span>); <span class="hljs-built_in">let</span> button = document.getElementById(<span class="hljs-string">'button'</span>); button.addEventListener(<span class="hljs-string">'click'</span>, e => { <span class="hljs-built_in">let</span> script = document.createElement(<span class="hljs-string">'script'</span>); <span class="hljs-built_in">let</span> <span class="hljs-keyword">function</span>Name = <span class="hljs-string">'lvbin'</span> + parseInt(Math.random() * 100000, 10); window[<span class="hljs-keyword">function</span>Name] = <span class="hljs-keyword">function</span> (result) { <span class="hljs-keyword">if</span> (result === <span class="hljs-string">'success'</span>) { money.innerText = money.innerText - 1; } } script.src = <span class="hljs-string">'/pay?callback='</span> + <span class="hljs-keyword">function</span>Name; document.body.appendChild(script); script.onload = e => { e.currentTarget.remove(); delete window[<span class="hljs-keyword">function</span>Name]; }; script.onerror = e => { e.currentTarget.remove(); delete window[<span class="hljs-keyword">function</span>Name]; }; });
server.jsコード:
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ファイルコード:
100

転載先:https://juejin.im/post/5c8a23a1f265da2dbf5f4acd