简体   繁体   English

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

[英]Not allowed to load local resource using expressjs

I am trying to load an image file from a string (the filename) inside of a text file: 我试图从文本文件中的字符串(文件名)加载图像文件:

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

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

However, when the page loads, I get this error: 但是,当页面加载时,我收到此错误:

Not allowed to load local resource

On forums like this one: http://www.sencha.com/forum/showthread.php?200512-Not-allowed-to-load-local-resource I found advice saying that I should serve the file directory through HTTP. 在像这样的论坛上: http//www.sencha.com/forum/showthread.php? 200512-Not-allowed-to-load-local- resource我发现建议说我应该通过HTTP服务文件目录。 The thing is, my entire application is built on Express, so it already is using http to serve files. 问题是,我的整个应用程序都是基于Express构建的,因此它已经使用http来提供文件。 Any ideas as to what I'm doing wrong here? 关于我在这里做错了什么想法?

Your problem is related to Same origin policy . 您的问题与Same origin策略有关 If you are using express you can do something like this: 如果你使用快递,你可以这样做:

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', {});
}
});

This will write your image to the stream. 这会将您的图像写入流。 You can also provide your image via a fileserver or webserver serving static files and then access it from your jade tmeplate via http. 您还可以通过提供静态文件的文件服务器或网络服务器提供您的图像,然后通过http从您的玉器tomeplate访问它。 Due to the policy mentioned above you can not load local resources like file://path/to/local/file 由于上述策略,您无法加载本地资源,例如file:// path / to / local / file

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

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