如何在Node.js的发送文件之前设置一个MIME类型? [英] How do I set a MIME type before sending a file in Node.js?
问题描述
当发送从我的Node.js服务器脚本的浏览器,谷歌浏览器,我得到这样的警告:
When sending scripts from my Node.js server to the browser, in Google Chrome, I get this warning:
资源间preTED为脚本,但MIME类型转移
纯文本/
Resource interpreted as Script but transferred with MIME type text/plain
我Google'd四周,发现这是一个服务器端的问题,即,我认为我应该设置正确的MIME类型的东西,送他们。这里的HTTP服务器的处理程序:
I Google'd around, and found out that it's a server-side problem, namely, I think that I should set the correct MIME type to things, before sending them. Here's the HTTP server's handler:
var handler = function(req, res)
{
url = convertURL(req.url); //I implemented "virtual directories", ignore this.
if (okURL(url)) //If it isn't forbidden (e.g. forbidden/passwd.txt)
{
fs.readFile (url, function(err, data)
{
if (err)
{
res.writeHead(404);
return res.end("File not found.");
}
//I think that I need something here.
res.writeHead(200);
res.end(data);
});
}
else //The user is requesting an out-of-bounds file.
{
res.writeHead(403);
return res.end("Forbidden.");
}
}
问:如何纠正我的服务器端code正确配置MIME类型
(注:我已经找到 https://github.com/broofa/node-mime ,但只有它让我确定MIME类型,而不是套了。)
(Note: I already found https://github.com/broofa/node-mime, but it only lets me determine the MIME type, not to "set" it.)
推荐答案
我想它了!
感谢@ rdrey的链接和的 我设法正确设置MIME类型的响应,该节点模块是这样的:
Thanks to @rdrey's link and this node module I managed to correctly set the MIME type of the response, like this:
function handler(req, res) {
var url = convertURL(req.url);
if (okURL(url)) {
fs.readFile(url, function(err, data) {
if (err) {
res.writeHead(404);
return res.end("File not found.");
}
res.setHeader("Content-Type", mime.lookup(url)); //Solution!
res.writeHead(200);
res.end(data);
});
} else {
res.writeHead(403);
return res.end("Forbidden.");
}
}
这篇关于如何在Node.js的发送文件之前设置一个MIME类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!