一、什么是 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' }));
到此这篇关于在node.js中设置响应的mime类型的代码详解的文章就介绍到这了,更多相关node.js设置mime类型内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论