灏天阁

NODEJS[26]:http模块_设置mime类型

· Yin灏

媒体类型是一种标准,用来表示文档、文件或字节流的性质和格式。

mime 类型结构:[type]/[subType]
例如:text/html text/css image/jpeg image/png application/json

HTTP 服务可以奢姿响应头 content-type 来表明响应体的 MIME 类型,

下面是常见文件对应的 mime 类型:

  1. html: text/html

  2. css: text/css

  3. js: text/javascript

  4. png: image/png

  5. jpg: image/jpeg

  6. git: image/gif

  7. mp4: video/mp4

  8. mp3: audio/mp3

  9. json: application/json

对于未知资源类型,可以选择 application/octet-stream

演示

const http = require("http");
const fs = require("fs");
const path = require("path");
let mimes = {
  html: "text/html",
  css: "text/css",
  js: "text/javascript",
  png: "image/png",
  jpg: "image/jpeg",
  git: "image/gif",
  mp4: "video/mp4",
  mp3: "audio/mp3",
  json: "application/json",
};
const server = http.createServer((request, response) => {
  let { pathname } = new URL(request.url, "http://127.0.0.1");
  // 拼接文件路径
  let filePath = __dirname + "/page" + pathname;
  // 读取文件
  fs.readFile(filePath, (err, data) => {
    if (err) {
      response.statusCode = 500;
      response.end("文件读取失败");
      return;
    }
    let ext = path.extname(filePath).slice(1);
    // ";charset=utf-8" 处理乱码
    // 这里优先级更高
    response.setHeader(
      "content-type",
      mimes[ext] || "application/octet-stream" + ";charset=utf-8"
    );
    /*
      方式2:只针对 html 设置字符集,其他 css、js 等文件会向它看齐
      if(ext === 'html') {
        response.setHeader("content-type", mimes[ext] ||"application/octet-stream" + ";charset=utf-8"
      );
      } else {
        response.setHeader("content-type", mimes[ext] ||"application/octet-stream"
      }
    */
    response.end(data);
  });
});
server.listen(9000, () => {
  cons.log("服务器已经启动了...");
});

- Book Lists -