从Azure

时间:2017-05-17 12:02:46

标签: node.js azure express cors

我有一个应用程序,我使用Photosphereviewer js来显示图像。

我使用了node.js应用程序并将其上传到Azure网站(例如:http://example1.com)。 Photosphereviewer中使用的图像来自其他网站(例如:https://example2.com)。

现在,当我从http://example1.com访问图像时,它会抛出错误,如下所示

  

从原点“https://example2.com/images/1.JPG”访问图像   CORS政策已阻止“http://example1.com”:否   请求中存在“Access-Control-Allow-Origin”标头   资源。因此不允许来源“http://example1.com”   访问。

当我尝试使用其他网站中的图像时,它会正确显示图像而不会出错。

但是,当我在Photosphereviewer中使用如下图像时,它会引发cors错误:

var PSV = new PhotoSphereViewer({
                    panorama: 'https://example2.com/images/1.JPG',
                    container: 'photosphere',
                    caption: 'Images',
                    cors_anonymous: true,
                    checkImageOrigin: false,
                    // loading_img: 'http://photo-sphere-viewer.js.org/assets/photosphere-logo.gif',
                    navbar: 'autorotate zoom download caption', // fullscreen
                    // default_fov: 70,
                    mousewheel: false,
                    size: {
                      height: 520//472
                    }
                });

我在node js app的app.js中使用了cors,如下所示:

app.use(cors());
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*'); // We can access from anywhere
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');

  next();
});

在Azure网站中,我已将网站名称包含在Api部分下的CORS选项下。

但都没有效果。它会抛出同样的错误。请帮助克服这个问题。提前致谢。

1 个答案:

答案 0 :(得分:0)

似乎您提供图片的网站example2具有以下快速静态设置:
app.use(express.static('public'));
您的图像文件可能列在目录public/images下。

我在上述环境中重现了您的问题。

您可以尝试在expressjs服务器中构建单独的路由,为PhotoSphereViewer客户端提供图像:

app.get('/getimages/:filename',(req,res)=>{
  res.sendFile(__dirname+'/public/images/'+req.params.filename)
})

在forntend中:

var PSV = new PhotoSphereViewer({
                panorama: 'https://example2.azurewebsites.net/getimages/1.jpg',
                container: 'photosphere',
                caption: 'Images',
                cors_anonymous: true,
                checkImageOrigin: false,
                // loading_img: 'http://photo-sphere-viewer.js.org/assets/photosphere-logo.gif',
                navbar: 'autorotate zoom download caption', // fullscreen
                // default_fov: 70,
                mousewheel: false,
                size: {
                  height: 520//472
                }
            });