2人参与 • 2025-04-24 • Javascript
mime(multipurpose internet mail extensions)类型用于告诉浏览器或客户端:返回的数据是什么类型的内容。
例如:
text/html
:html 文件application/json
:json 数据text/css
:css 样式表image/png
:png 图片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 模块。
npm install mime
const mime = require('mime'); const filepath = 'public/style.css'; const contenttype = mime.gettype(filepath); // 返回 'text/css'
扩展名 | 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
是告诉浏览器怎么处理数据的关键;content-type
,浏览器可能会猜测类型,但这不安全;res.writehead(200, { 'content-type': 'application/json' }); res.end(json.stringify({ message: 'hello' }));
到此这篇关于在node.js中设置响应的mime类型的代码详解的文章就介绍到这了,更多相关node.js设置mime类型内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论