daxia 2 жил өмнө
parent
commit
8afa8c2546

+ 6 - 2
19_Node.js/day-2/code/index.js

@@ -15,5 +15,9 @@
 
 // otherMethods();
 
-import { run } from './learn:url.mjs';
-run();
+// import { run } from './learn:url.mjs';
+// run();
+
+import { start } from './learn:http.mjs';
+
+start();

+ 46 - 0
19_Node.js/day-2/code/learn:http.mjs

@@ -0,0 +1,46 @@
+import { Server } from 'node:http';
+
+const app = new Server();
+
+// app.on('connect', (request) => {
+//   console.info('有客户端连接进来...', request);
+// });
+
+// app.on('close', () => {
+//   console.info('有某个客户端断开连接...');
+// });
+
+app.on('request', (request, response) => {
+  console.log(request);
+  console.log('有请求进来...');
+  // response.write('hello');
+  // // response.end(); // end方法可以通知客户端响应结束
+  // response.end(' world.');
+  // response.setHeader('Content-Type', 'text/plain');
+  // response.end('<div><strong>hello, node.js!</strong></div>');
+  response.writeHead(200, 'yes', {
+    'Content-Type': 'application/json',
+  });
+
+  response.end(
+    JSON.stringify({
+      code: 1,
+      data: [
+        {
+          id: 1,
+          title: '吃饭',
+          done: false,
+        },
+      ],
+      msg: 'ok',
+    })
+  );
+});
+
+export function start(port = 8080, domain = 'localhost') {
+  // 开启http服务,并监听所有连接
+  app.listen(port, domain, () => {
+    // 监听8080以及服务都启动成功
+    console.log(`Server is running at port ${port}`);
+  });
+}