如何在 Node.js 中发送文件之前设置 MIME 类型? [英] How do I set a MIME type before sending a file in Node.js?

查看:33
本文介绍了如何在 Node.js 中发送文件之前设置 MIME 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的 Node.js 服务器向浏览器发送脚本时,在 Google Chrome 中,我收到此警告:

When sending scripts from my Node.js server to the browser, in Google Chrome, I get this warning:

资源被解释为脚本但使用 MIME 类型传输文本/纯文本

Resource interpreted as Script but transferred with MIME type text/plain

我谷歌了一下,发现这是一个服务器端问题,也就是说,我认为我应该在发送之前为事物设置正确的 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.");
    }
}

问题:如何更正服务器端代码以正确配置 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆