Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - How do I set a MIME type before sending a file in Node.js?

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

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

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

Question: How do I correct my server-side code to configure the MIME type correctly?

(Note: I already found https://github.com/broofa/node-mime, but it only lets me determine the MIME type, not to "set" it.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I figured it out!

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...