it编程 > 编程语言 > Javascript

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

2人参与 2025-04-24 Javascript

一、什么是 mime 类型(content-type)?

mime(multipurpose internet mail extensions)类型用于告诉浏览器或客户端:返回的数据是什么类型的内容

例如:

二、手动设置 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 模块。

安装:

npm install mime

使用:

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

四、注意事项

res.writehead(200, { 'content-type': 'application/json' });
res.end(json.stringify({ message: 'hello' }));

到此这篇关于在node.js中设置响应的mime类型的代码详解的文章就介绍到这了,更多相关node.js设置mime类型内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

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

04-24

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

04-24

通过Vue实现Excel文件的上传和预览功能

04-24

如何利用SpringBoot与Vue3构建前后端分离项目

04-24

JavaScript获取和操作时间戳的用法详解

04-24

在Vue项目中引入Echarts绘制K线图的方法技巧

04-24

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论