Node创建服务,响应接口请求

196 阅读1分钟

文件在同一目录下

// index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script>
  </head>
  <body>
    <script>
      $.ajax({
        url: "http://127.0.0.1:8080/" + new Date().getTime(),
        method: "POST",
        data: "im data",
        success: function (data) {
          console.log(data);
        }
      });
    </script>
  </body>
</html>
// app.js
var http = require("http");
var fs = require("fs");
let dataTxt;
fs.readFile("data.txt", function (err, params) {
  if (err) throw err;
  dataTxt = params;
});
function onRes(req, res) {
  // 解决跨域的请求
  res.writeHead(200, {
    "Content-Type": "text/plain",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS"
  });
  let postData = "";
  req.setEncoding("utf8");
  req.on("data", function (chunk) {
    postData = chunk;
  });

  // 返回request中的参数
  // req.on("end", function () {
  //   res.end(postData);
  // });

  // 返回data.txt文件中的数据
  req.on("end", function () {
    res.end(dataTxt);
  });
}
http.createServer(onRes).listen(8080);
console.log("服务器启动完成");
//data.json
{"id":"123",name:"jack",arg:321,remark:"test data"}