在 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 類型示例
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 類型 |
---|---|
.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 時推薦:
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'hello' }));