简体   繁体   中英

mime type node.js express

I am using node.js with express for a special webserver. 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. 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. I also tried res.set('Content-Type', ...), res.header(...), using res.send(new Buffer(data.toString(), 'utf8')) with the mime type set before. No matter what i do in chrome its allways text/html. If i inspect the returned headers there isnt even a Content-Type field in the header.

What am I doing wrong here? Thanks for your advices.

My advice, why not use Express static middleware ?

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

It should handle 404 errors, caching, mime types, etc. for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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