node.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > node.js > Node.js设置MIME类型

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

作者:前端涂涂

在 Node.js 中设置响应的 MIME 类型是为了让浏览器正确解析服务器返回的内容,比如 HTML、CSS、图片、JSON 等,我们通常通过设置响应头中的 Content-Type 字段来完成,本文就给大家详细介绍了在Node.js中设置响应的MIME类型的方法,需要的朋友可以参考下

一、什么是 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类型内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文