简体   繁体   English

MIME类型node.js express

[英]mime type node.js express

I am using node.js with express for a special webserver. 我正在将node.js和express用于特殊的Web服务器。 Most of it wont actually cover the work a standard webserver does but for a small part i need it to behave like a regular webserver, so read a file, send its content with the appropriate mime type to the client and thats it. 它的大部分实际上不会涵盖标准Web服务器所做的工作,但是有一小部分,我需要它表现得像常规Web服务器一样,因此读取文件,将其内容以适当的mime类型发送给客户端,就这样。 Currently my code looks like this: 目前,我的代码如下所示:

app.get('/ui/*', function(req, res) {
    var file = '../M4Editor/data' + req.url;
    fs.readFile(file, { encoding: "utf8" }, function(err, data) {
        if(err) {
            res.send(404);
            return;
        }

        res.type(mime.lookup(file));
        res.send(data.toString());
    });    
});

mime.lookup returns the correct result. mime.lookup返回正确的结果。 I also tried res.set('Content-Type', ...), res.header(...), using res.send(new Buffer(data.toString(), 'utf8')) with the mime type set before. 我还尝试使用带有mime类型的res.send(new Buffer(data.toString(),'utf8'))尝试使用res.set('Content-Type',...),res.header(...)设置之前。 No matter what i do in chrome its allways text/html. 无论我在Chrome中做什么,始终使用text / html。 If i inspect the returned headers there isnt even a Content-Type field in the header. 如果我检查返回的标头,则标头中甚至没有Content-Type字段。

What am I doing wrong here? 我在这里做错了什么? Thanks for your advices. 感谢您的建议。

My advice, why not use Express static middleware ? 我的建议,为什么不使用Express静态中间件

app.use('/ui', express.static(__dirname + '../M4Editor/data'));

It should handle 404 errors, caching, mime types, etc. for you. 它应该为您处理404错误,缓存,mime类型等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM