learn:http.mjs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { Server } from 'node:http';
  2. const app = new Server();
  3. // app.on('connect', (request) => {
  4. // console.info('有客户端连接进来...', request);
  5. // });
  6. // app.on('close', () => {
  7. // console.info('有某个客户端断开连接...');
  8. // });
  9. app.on('request', (request, response) => {
  10. console.log(request);
  11. console.log('有请求进来...');
  12. // response.write('hello');
  13. // // response.end(); // end方法可以通知客户端响应结束
  14. // response.end(' world.');
  15. // response.setHeader('Content-Type', 'text/plain');
  16. // response.end('<div><strong>hello, node.js!</strong></div>');
  17. response.writeHead(200, 'yes', {
  18. 'Content-Type': 'application/json',
  19. });
  20. response.end(
  21. JSON.stringify({
  22. code: 1,
  23. data: [
  24. {
  25. id: 1,
  26. title: '吃饭',
  27. done: false,
  28. },
  29. ],
  30. msg: 'ok',
  31. })
  32. );
  33. });
  34. export function start(port = 8080, domain = 'localhost') {
  35. // 开启http服务,并监听所有连接
  36. app.listen(port, domain, () => {
  37. // 监听8080以及服务都启动成功
  38. console.log(`Server is running at port ${port}`);
  39. });
  40. }