Node入门之实现已一个简单http服务(html页面、css、json数据、静态资源)

375 阅读4分钟

Node入门之实现简单http服务

实现一个简单http服务(html页面、css、json数据、静态资源)

1、创建一个http服务器, http.js

const http = require("http");

const server = http.createServer((request, response) => {
  response.end("Hello World");
});

server.listen(8080, () => {
  console.log("localhost:8080");
});

在浏览器输入localhost:8080可以看到 Hello World

2、显示首页

2.1新建index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>node-study</title>
</head>
<body>
    <h1>Hello Node</h1>
</body>
</html>

2.2 修改http.js,返回首页

  1. 处理404情况
  2. 服务器使用fs.readFile()读取index.html文件数据
  3. 处理err
  4. 返回index.html给客户端
const http = require("http");
const fs = require("fs");

const server = http.createServer((request, response) => {
  const { url, method } = request;
  if (url === "/" && method === "GET") {
    // fs.readFile()读取index.html
    fs.readFile("index.html", (err, data) => {
      if (err) {
        // 处理err
        response.writeHead(500, { "Content-Type": "text/plain;charset=utf-8" });
        response.end("500, 服务器错误");
        return;
      } else {
        // 返回数据给客户端
        response.statusCode = 200;
        response.setHeader("Content-Type", "text/html");
        response.end(data);
      }
    });
  } else {
    // 处理404
    response.statusCode = 404;
    response.setHeader("Content-Type", "text/plain;charset=utf-8");
    response.end("404, 页面没有找到");
  }
});

server.listen(8080, () => {
  console.log("localhost:8080");
});

3、编写一个get接口

在http.js文件中增加如下代码

else if (url === '/user' && method === "GET") {
    response.statusCode = '200'
    response.setHeader('Content-Type', "application/json")
    response.end(JSON.stringify({name: '小明', age: 20}))
}

请求接口 http://localhost:8080/user

4、添加对css的支持

4.1 新建index.css

h1 {
  color: red;
}

4.2 index.html引入index.css

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>node-study</title>
    <!-- 引入css -->
    <link rel="stylesheet" href="index.css" >
</head>
<body>
    <h1>Hello Node</h1>
</body>
</html>

做完以上两步,刷新页面可以看到请求css文件时返回404. image.png

4.3 修改http.js使客户端可以正常获取css文件

在上面的图片中可以看到请求 xx.css文件时,请求头中Accept属性中有字符串text/css,可以通过fs.createReadStream()方法创建一个可读流,读取index.css文件,再创建管道把可读流中的输出传递给response

const { url, method, headers } = request;
else if (method === "GET" && headers.accept.indexOf("text/css") !== -1) {
    // 创建可读流,并把数据通过管道和返回参数response连接
    fs.createReadStream("." + url).pipe(response);
}

http.js

const http = require("http");
const fs = require("fs");

const server = http.createServer((request, response) => {
  const { url, method, headers } = request;
  if (url === "/" && method === "GET") {
    // 读取index.html
    fs.readFile("index.html", (err, data) => {
      if (err) {
        // 处理err
        response.writeHead(500, { "Content-Type": "text/plain;charset=utf-8" });
        response.end("500, 服务器错误");
        return;
      } else {
        // 返回数据给客户端
        response.statusCode = 200;
        response.setHeader("Content-Type", "text/html");
        response.end(data);
      }
    });
  } else if (url === "/user" && method === "GET") {
    response.statusCode = "200";
    response.setHeader("Content-Type", "application/json");
    response.end(JSON.stringify({ name: "小明", age: 20 }));
  } else if (method === "GET" && headers.accept.indexOf("text/css") !== -1) {
    // 创建可读流,并把数据通过管道和返回参数response连接
    fs.createReadStream("." + url).pipe(response);
  } else {
    // 处理404
    response.statusCode = 404;
    response.setHeader("Content-Type", "text/plain;charset=utf-8");
    response.end("404, 页面没有找到");
  }
});

server.listen(8080, () => {
  console.log("localhost:8080");
});

重启服务,刷新页面可以看到index.css文件请求成功,标题颜色变红

5、添加js文件支持

5.1、 新建js文件hello.js

console.log('Hello World!')

5.2、 修改index.html引入hello.js

5.3、 修改http.js使客户端可以正常获取文件

else if (method === "GET" && url.endsWith(".js")) {
    // 创建可读流,并把数据通过管道和返回参数response连接
    fs.createReadStream("." + url).pipe(response);
}

6、增加http服务对图片、音频和视频等文件的支持

else if (method === "GET" && headers.accept.indexOf("image/*") !== -1) {
    // 支持图片文件、创建可读流,并把数据通过管道和返回参数response连接
    fs.createReadStream("." + url).pipe(response);
} else if (method === "GET" && headers.accept === "*/*") {
    // 支持音频、视频或者其他文件 创建可读流,并把数据通过管道和返回参数response连接
    fs.createReadStream("." + url).pipe(response);
}

http.js

const http = require("http");
const fs = require("fs");

const server = http.createServer((request, response) => {
  const { url, method, headers } = request;
  if (url === "/" && method === "GET") {
    // 读取index.html
    fs.readFile("index.html", (err, data) => {
      if (err) {
        // 处理err
        response.writeHead(500, { "Content-Type": "text/plain;charset=utf-8" });
        response.end("500, 服务器错误");
        return;
      } else {
        // 返回数据给客户端
        response.statusCode = 200;
        response.setHeader("Content-Type", "text/html");
        response.end(data);
      }
    });
  } else if (url === "/user" && method === "GET") {
    response.statusCode = "200";
    response.setHeader("Content-Type", "application/json");
    response.end(JSON.stringify({ name: "小明", age: 20 }));
  } else if (method === "GET" && headers.accept.indexOf("text/css") !== -1) {
    // 支持css文件、创建可读流,并把数据通过管道和返回参数response连接
    fs.createReadStream("." + url).pipe(response);
  } else if (method === "GET" && url.endsWith(".js")) {
    // 支持js文件、创建可读流,并把数据通过管道和返回参数response连接
    fs.createReadStream("." + url).pipe(response);
  } else if (method === "GET" && headers.accept.indexOf("image/*") !== -1) {
    // 支持图片文件、创建可读流,并把数据通过管道和返回参数response连接
    fs.createReadStream("." + url).pipe(response);
  } else if (method === "GET" && headers.accept === "*/*") {
    // 支持音频、视频或者其他文件 创建可读流,并把数据通过管道和返回参数response连接
    fs.createReadStream("." + url).pipe(response);
  } else {
    // 处理404
    response.statusCode = 404;
    response.setHeader("Content-Type", "text/plain;charset=utf-8");
    response.end("404, 页面没有找到");
  }
});

server.listen(8080, () => {
  console.log("localhost:8080");
});

http服务最终支持的文件类型如下 image.png


代码地址: github.com/banixing/no…
参考资料: