1.核心实现步骤

image.png

  1. const http = require('http')
  2. const server = http.createServer((req, res) => {
  3. const url = req.url // 1.获取请求的url地址
  4. var content = '<h1>404 Not Found!</h1>' // 2.设置默认的响应内容为404 not found
  5. if (url === '/' || url === '/index.html') {
  6. content = '<h1>首页</h1>' // 3. 当用户请求的是首页
  7. } else if (url === '/about.html') {
  8. content = '<h1>关于页面</h1>' // 4. 用户请求的是关于页面
  9. }
  10. res.setHeader('content-type', 'text/html; charset=utf-8') // 5. 设置content-type响应头,防止中文乱码
  11. res.end(content) // 6. 把内容发送给客户端
  12. }).listen(80, () => {
  13. console.log('服务器已经启动在 http://localhost');
  14. })