Parse.com 和 Fabric.js,如何修复托管图像的 CORS 错误

Parse.com and Fabric.js, how to fix CORS error for hosted images

我正在使用 Parse.com 为移动应用程序存储图像文件。图像被正确存储和检索。问题是当图像被添加到 FabricJS canvas 时,canvas 被标记为 "tainted",因此无法保存(使用 canvas.toDataURL)。

我尝试添加 "crossOrigin" 选项:

fabric.Image.fromURL( ... parse.com url .. , function(img) {
            img.set({
              left: 10,
              top: 10
            });
            $scope.canvas.add(img);
            $scope.canvas.setActiveObject(img);
          }, { "crossOrigin" : "anonymous" } );

但是这返回了错误:

Image from origin 'http://files.parsetfss.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access.

我找不到在 Parse.com 中添加上面的 header 的方法。我也无法实现代理服务器,因为这是使用 Parse.com.

的全部意义所在

非常感谢您的帮助,谢谢。

使用 Parse.com "Cloud Code" 找到了解决方案。步骤如下:

  1. 在Parse.com中创建代理服务器(用Express编写)。此代理服务器添加 CORS headers.
// These two lines are required to initialize Express in Cloud Code.
var express = require('express');
var app = express();

// Global app configuration section
app.set('views', 'cloud/views');  // Specify the folder to find templates
app.set('view engine', 'ejs');    // Set the template engine
app.use(express.bodyParser());    // Middleware for reading request body

//
// Example request:
// http://files.parsetfss.com/XXX/YYY
//
app.get('/images/:tag1/:tag2', function(req, res) {

  Parse.Cloud.httpRequest({
    url: 'http://files.parsetfss.com/' + req.params.tag1 + "/" + req.params.tag2,
    success: function(httpResponse) {
      // add CORS headers
      res.set("Access-Control-Allow-Origin", "*");
      res.set("Access-Control-Allow-Headers", "X-Requested-With");
      res.set('Access-Control-Allow-Headers', 'Content-Type');

      res.send(httpResponse.buffer);
    },
    error: function(err) {
      console.log(err);
      res.send('Error finding file');
    }
  });

});

// Attach the Express app to Cloud Code.
app.listen();

有关在 Parse.com 上设置 Cloud Code 的更多详细信息,请参见此处:https://parse.com/docs/js/guide#cloud-code

  1. 更新 FabricJS 调用以将 crossOrigin 设置为 "anonymous" 并将调用重定向到您的代理服务器。
        var url = <originalimageurl>;
        url = url.replace("http://files.parsetfss.com/", 
                          "http:\/\/<parsecom-domain>.parseapp.com\/images\/");
        fabric.Image.fromURL(url, function(img) {
            img.set({
              left: 10,
              top: 10
            });
            $scope.canvas.add(img);
            $scope.canvas.setActiveObject(img);
          }, { "crossOrigin" : "anonymous" } );

<originalimageurl>替换为存储在Parse.com中的原始图像url。 将 <parsecom-domain> 替换为您在 Parse.com.

中的子域

这将起作用,因为客户端 (FabricJS) 和代理服务器 (Parse.com CloudCode) 支持 CORS。创建的图像将不再被视为跨源,因此 canvas 不会被污染。终于,canvas现在可以得救了!

我希望这对其他人有帮助。干杯。