不允许使用expressjs加载本地资源

时间:2013-04-22 06:26:19

标签: javascript node.js express

我正在尝试从文本文件中的字符串(文件名)加载图像文件:

var thisItem = ITEM_COLLECTION_FILE_NAME;
var rs = fs.createReadStream(path.resolve(thisItem));

rs.on("data", function(data) {
if (data) {
lines += data;
}
});

但是,当页面加载时,我收到此错误:

Not allowed to load local resource

在像这样的论坛上:http://www.sencha.com/forum/showthread.php?200512-Not-allowed-to-load-local-resource我发现建议说我应该通过HTTP提供文件目录。问题是,我的整个应用程序都是基于Express构建的,因此它已经使用http来提供文件。关于我在这里做错了什么想法?

1 个答案:

答案 0 :(得分:2)

您的问题与Same origin policy有关。如果你使用快递,你可以这样做:

app.get('/img', function(req, res){
try{
    var full_path = /full/path/to/your/local/file

    fs.exists(full_path, function(exists){
        if(!exists){
            res.render('404.jade', {});
        }else{
            fs.readFile(full_path, "binary", function(err, file) {
                    res.writeHeader(200);  
                    res.write(file, "binary"); 
                    res.end();
            });
        }
    });
}catch (err){
    res.render('500.jade', {});
}
});

这会将您的图像写入流中。您还可以通过提供静态文件的文件服务器或网络服务器提供您的图像,然后通过http从您的玉器tomeplate访问它。由于上述策略,您无法加载本地资源,例如file:// path / to / local / file