在 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' }));

相关推荐
MiyueFE11 分钟前
Nuxt 4.0 深度解析:从架构革新到实战迁移 🚀
前端·nuxt.js
天天向上的鹿茸13 分钟前
web前端用MVP模式搭建项目
前端·javascript·设计模式
暖木生晖1 小时前
动画序列——实现一个div转一圈的效果
前端·css·html·css3·html5
山河木马1 小时前
前端学C++可太简单了:导入标准库
前端·javascript·c++
Hilaku1 小时前
你不会使用css函数 clamp()?那你太low了😀
前端·css·html
三小河1 小时前
解决小项目中的频繁部署-适用于没有Jenkins或者没有配置流水线的前端部署
前端
胡gh1 小时前
线程与进程:从零开始理解它们的区别与联系
前端·javascript·后端
OEC小胖胖1 小时前
React Native 在 Web 前端跨平台开发中的优势与实践
前端·react native·react.js·前端框架·web
精神小伙2号1 小时前
vue的provide和inject
前端·javascript·vue.js