如何在Node.js中发送文件之前设置MIME类型?

问题描述 投票:19回答:4

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

资源解释为脚本,但使用MIME类型text / plain传输

我谷歌了,并发现这是一个服务器端问题,即我认为我应该在发送之前设置正确的MIME类型。这是HTTP服务器的处理程序:

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类型,而不是“设置”它。)

javascript node.js browser webserver
4个回答
19
投票

我想到了!

感谢@ rdrey的linkthis node module我设法正确设置了响应的MIME类型,如下所示:

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.");
    }
}

7
投票

在Google上搜索Content-Type HTTP标头。

然后弄清楚如何用http://expressjs.com/api.html#res.set设置它

哎呀,这个例子包括你的答案;)

只需检查文件结尾,如果是.js,请设置适当的MIME类型以使浏览器满意。

编辑:如果这是纯节点,没有表达,请看这里:http://nodejs.org/api/http.html#http_response_setheader_name_value


3
投票

mime.lookup()现在更名为mime.getType()。所以你可以这样做:

res.set('Content-Type', mime.getType('path/file'));

https://www.npmjs.com/package/mime


2
投票

我在处理函数时遇到问题,因为convertURL和okURL函数没有定义。我修改了一点代码,看起来像这样

function handler(req, res) 
{
    // /home/juan/Documentos/push-api-demo is the path of the root directory of the server
    var url             = '/home/juan/Documentos/push-api-demo' + req.url;
    var file_exists     = fs.existsSync(url);

    if (file_exists) 
    {
        fs.readFile(url, function(err, data) 
        {
            if (err) 
            {
                res.writeHead(404);
                return res.end("File not found.");
            }

            res.setHeader("Content-Type", mime.lookup(url)); 
            res.writeHead(200);
            res.end(data);
        });
    } 
    else 
    {
        res.writeHead(403);
        return res.end("Forbidden.");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.