在 Node.js 中设置响应的 MIME 类型

在 Node.js 中设置响应的 MIME 类型是为了让浏览器正确解析服务器返回的内容,比如 HTML、CSS、图片、JSON 等。我们通常通过设置响应头中的 Content-Type 字段来完成。


✅ 一、什么是 MIME 类型(Content-Type)?

MIME(Multipurpose Internet Mail Extensions)类型用于告诉浏览器或客户端:返回的数据是什么类型的内容

例如:

  • text/html:HTML 文件
  • application/json:JSON 数据
  • text/css:CSS 样式表
  • image/png:PNG 图片

✅ 二、手动设置 MIME 类型示例

js 复制代码
const http = require('http');
const fs = require('fs');
const path = require('path');

// 常见扩展名与 MIME 类型的映射表
const mimeTypes = {
  '.html': 'text/html',
  '.css':  'text/css',
  '.js':   'application/javascript',
  '.json': 'application/json',
  '.png':  'image/png',
  '.jpg':  'image/jpeg',
  '.gif':  'image/gif',
  '.svg':  'image/svg+xml',
  '.ico':  'image/x-icon',
  '.txt':  'text/plain',
};

const server = http.createServer((req, res) => {
  let filePath = '.' + (req.url === '/' ? '/index.html' : req.url);
  let ext = path.extname(filePath);

  // 默认 MIME 类型
  let contentType = mimeTypes[ext] || 'application/octet-stream';

  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      return res.end('404 Not Found');
    }

    res.writeHead(200, { 'Content-Type': contentType });
    res.end(data);
  });
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

✅ 三、使用第三方模块 mime

如果你不想维护 MIME 映射表,可以使用官方推荐的 mime 模块。

安装:

bash 复制代码
npm install mime

使用:

js 复制代码
const mime = require('mime');
const filePath = 'public/style.css';
const contentType = mime.getType(filePath); // 返回 'text/css'

✅ 常用 MIME 类型一览

扩展名 MIME 类型
.html text/html
.css text/css
.js application/javascript
.json application/json
.png image/png
.jpg image/jpeg
.gif image/gif
.svg image/svg+xml
.txt text/plain
.pdf application/pdf

✅ 四、注意事项

  • Content-Type告诉浏览器怎么处理数据的关键;

  • MIME 类型必须与实际资源类型匹配,否则浏览器可能拒绝渲染或报错;

  • 若未设置 Content-Type,浏览器可能会猜测类型,但这不安全;

  • 返回 JSON 时推荐:

    js 复制代码
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'hello' }));

相关推荐
八角丶12 小时前
Node.js Cluster 详解
前端·node.js
濮水大叔16 小时前
CabloyJS 强大之处不仅仅是 IoC,而是全栈资源的寻址体系
typescript·node.js·全栈
烂蜻蜓16 小时前
Node.js入门教程(二十六):内置模块
node.js
东方小月17 小时前
从零开发一个 Coding Agent(十一):实现 CLI 的 print 模式
node.js·全栈
__zRainy__18 小时前
Node系列 · Node基础:ES 模块化
node.js
FungLeo19 小时前
Node 后端实战 · 后端敏感数据怎么防泄露?PII 自动脱敏与审计日志实战
node.js·数据脱敏·数据防泄漏·pii 脱敏
深念Y19 小时前
Opencode Event 表写入优化方案
数据库·人工智能·ai·node.js·bug·优化·opencode
ikun778g20 小时前
DeepSeek Harness 本地部署保姆级教程:从 Node.js 24.0.0 安装到 WorkBuddy 一键运行
ai·node.js
烂蜻蜓1 天前
Node.js入门教程(二十三):全局对象
node.js·编辑器·vim
xywww1682 天前
Node.js Claude API 实战接入:SDK 调用 Opus 5、环境变量配置与报错排查
node.js