欢迎来到科站长!

JavaScript

当前位置: 主页 > 网络编程 > JavaScript

在Node.js中设置响应的MIME类型的代码详解

时间:2025-07-25 10:11:47|栏目:JavaScript|点击:

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

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

例如:

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

二、手动设置 MIME 类型示例

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 模块。

安装:

1
npm install mime

使用:

1
2
3
const mime = require('mime');
const filePath = 'public/style.css';
const contentType = mime.getType(filePath); // 返回 'text/css'

常用 MIME 类型一览

扩展名MIME 类型
.htmltext/html
.csstext/css
.jsapplication/javascript
.jsonapplication/json
.pngimage/png
.jpgimage/jpeg
.gifimage/gif
.svgimage/svg+xml
.txttext/plain
.pdfapplication/pdf

四、注意事项

  • Content-Type 是告诉浏览器怎么处理数据的关键;
  • MIME 类型必须与实际资源类型匹配,否则浏览器可能拒绝渲染或报错;
  • 若未设置 Content-Type,浏览器可能会猜测类型,但这不安全;
  • 返回 JSON 时推荐:
1
2
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'hello' }));


上一篇:Vue3解决Mockjs引入后并访问404(Not Found) 的页面报错问题

栏    目:JavaScript

下一篇:Node使用Puppeteer监听并打印网页的接口请求

本文标题:在Node.js中设置响应的MIME类型的代码详解

本文地址:https://fushidao.cc/wangluobiancheng/23792.html

广告投放 | 联系我们 | 版权申明

申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:257218569 | 邮箱:257218569@qq.com

Copyright © 2018-2025 科站长 版权所有冀ICP备14023439号