test.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. us = {};
  2. // us.qs = require("querystring"); //引用文件解析包
  3. // us.http = require("http"); //引用http server服务
  4. // 引入Express模块
  5. const express = require('express');
  6. const path = require('path');
  7. us.http = require("http"); //引用http server服务
  8. // 创建Express应用
  9. const app = express();
  10. // 设置静态文件目录
  11. app.use(express.static(path.join(__dirname, '/')));
  12. us.server = us.http.createServer(function (req, res) {
  13. // 定义路由
  14. // app.all('/', (req, res) => {
  15. //设置跨域
  16. res.writeHead(200, {
  17. "Content-Type": "application/json",
  18. 'Access-Control-Allow-Origin': '*',
  19. "Connection": "keep-alive",
  20. 'Access-Control-Allow-Headers': 'Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'
  21. });
  22. var data = [{ "name": "John", "age": 30 }];
  23. for (var i = 0; i < 100; i++) {
  24. data.push(data[0]);
  25. }
  26. setInterval(function () {
  27. res.write(JSON.stringify(data));
  28. }, 2000);
  29. });
  30. // 启动服务器
  31. app.listen(3000, () => {
  32. console.log('Server is running on port 3000');
  33. });
  34. /**
  35. * 监听1473端口的处理
  36. *
  37. **/
  38. us.server.listen('1473', '', function () {
  39. //在控制台输出监听提示
  40. console.log("开始监听" + us.server.address().port + "......");
  41. });