# 第六章 认识基于文本的 HTTP 协议

编写一个简单的 HTTP 服务器

// app.js
import { createServer } from "net";
const server = createServer((client) => {
  console.log("address", client.remoteAddress);
  console.log("port", client.remotePort);
  client.on("data", (chunk) => {
    console.log(chunk.toString());
    client.write(
      `HTTP/1.1 200 OK\r
      Content-Type: text/html\r
      Content-Length: 20\r\n
      <h1>Hello,World!</h1>`
    );
    client.end();
  });
});

server.listen(
  {
    host: "localhost",
    port: 3001
  },
  () => {
    console.log("http://localhost:3001");
  }
);

执行

npm install nodemon -g
nodemon server.js

查看 HTTP 响应报文

address 127.0.0.1
address 9021
GET /favicon.ico HTTP/1.1
Host: localhost:3001
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"
sec-ch-ua-mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: no-cors
Sec-Fetch-Dest: image
Referer: http://localhost:3001/
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,la;q=0.8,zh-TW;q=0.7,en;q=0.6,so;q=0.5