简体   繁体   English

AWS Cors Issue - Node.js

[英]AWS Cors Issue - Node.js

I am currently experiencing an issue when requesting images stored on AWS S3 (simple storage) with the CORS header. 当使用CORS标头请求存储在AWS S3(简单存储)上的图像时,我目前遇到了问题。 I have set up the CORS configuaration on the AWS console - and the setup is as follows: 我在AWS控制台上设置了CORS配置 - 设置如下:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

However, the response I get when requesting these images that I've stored are a little all over the place and quite intermittent. 但是,我在申请这些我存储的图像时得到的响应有点遍及整个地方并且非常间歇性。 Sometimes the image is returned with the headers requred and sometimes it is not. 有时图像会返回,并且需要标题,有时则不会。 I am really not sure why this happens. 我真的不确定为什么会这样。 It also seems that the effect worsens when I try to make more than one request for an image with the Access-Control-Allow-Origin header set as * on a page (eg If I need 10 images to be retrieved all with cross origin headers). 当我尝试在页面上将Access-Control-Allow-Origin标头设置为*时对图像进行多个请求时,效果似乎也会恶化(例如,如果我需要使用交叉原点标题检索10个图像)。

These are the headers that I need: 这些是我需要的标题:

Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3000

I'm really not sure what I'm doing incorrectly. 我真的不确定我做错了什么。 I have made sure that each image tag has the crossOrigin="anonymous" attribute added to it too, but again, no luck. 我确保每个图片标签都添加了crossOrigin =“anonymous”属性,但同样没有运气。

The reason for me needing these images to work cross origin is because I have installed an angular plugin which allows the user to crop images and store the cropped versions of the images as base64 strings. 我需要这些图像跨原点工作的原因是因为我安装了一个角度插件,允许用户裁剪图像并将图像的裁剪版本存储为base64字符串。 However, I get the following error when trying to retrive them. 但是,尝试检索它们时出现以下错误。

在此输入图像描述

These are the headers for an image that is returned correctly: 这些是正确返回的图像的标题:

Request URL:https://trajansmarket.s3.amazonaws.com/be5bbda0-b04a-11e5-81d3-dd7ff3efeebc.jpg
Request Method:GET
Status Code:304 Not Modified
Remote Address:54.231.252.131:443

Response Headers
view source
Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3000
Cache-Control:public, max-age=31536000
Date:Tue, 12 Jan 2016 21:13:03 GMT
ETag:"77bdbe9b517acc8cba86024c592bce3f"
Last-Modified:Fri, 01 Jan 2016 05:46:21 GMT
Server:AmazonS3
Vary:Origin, Access-Control-Request-Headers, Access-Control-Request-Method
x-amz-id-2:F3OQpOHsAqySk9LNwwoJXVATVIByr4Gtvz953ZoL7DdB/dtE9nYwo99R59Rj6RzZc3dcHyk6wWY=
x-amz-request-id:CD220FF1F6EE6CA9

Request Headers
view source
Accept:image/webp,image/*,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6,ms;q=0.4
Connection:keep-alive
Host:trajansmarket.s3.amazonaws.com
If-None-Match:"77bdbe9b517acc8cba86024c592bce3f"
Origin:http://91.121.220.161:3000
Referer:http://91.121.220.161:3000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36

And here's one without the headers: 而这里没有标题:

Request URL:https://trajansmarket.s3.amazonaws.com/c0671e00-b04a-11e5-81d3-
dd7ff3efeebc.jpg
Request Method:GET
Status Code:200 OK (from cache)
Remote Address:54.231.252.135:443

Response Headers
Accept-Ranges:bytes
Cache-Control:public, max-age=31536000
Content-Length:142102
Content-Type:application/octet-stream
Date:Tue, 12 Jan 2016 00:35:36 GMT
ETag:"beb93f56e3a2a65b983addd8af35c26c"
Last-Modified:Fri, 01 Jan 2016 05:46:25 GMT
Server:AmazonS3
x-amz-id-2:5XvaOd8bxMr5zwK317DfDMbk2+kzu3Zd7rsf2xl0hxwI40Oc4KDnQpgzD3sgtCRm9SXGqa93Mh0=
x-amz-request-id:FD3EB1978C38013B

Request Headers
Provisional headers are shown
Accept:image/webp,image/*,*/*;q=0.8
Origin:http://91.121.220.161:3000
Referer:http://91.121.220.161:3000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:498F45FE-5D49-4AE0-AF58-F81B9AFD48AF

I'm just wondering if anyone would have any idea of why this would be happening. 我只是想知道是否有人会知道为什么会发生这种情况。 Any help would be greatly appreciated. 任何帮助将不胜感激。

This was a very frustrating and I am still yet to work out the reason for AWS S3 intermittently returned the headers that I need for CORS. 这是非常令人沮丧的,我还没有弄清楚AWS S3间歇性地返回我需要的CORS标头的原因。

I have since thought of a workaround which is to 'download' and store the images that I need from amazon in a local folder - allow the user to 'crop' the image and store it before then deleting these images from the local folder. 我已经想到了一个解决方法,即“下载”并将我需要的图像从亚马逊存储在本地文件夹中 - 允许用户“裁剪”图像并存储它,然后从本地文件夹中删除这些图像。

To stream the image files to a local folder I used the fs.createWriteStream method on the .getObject method from s3. 为了将图像文件流式传输到本地文件夹,我在s3的.getObject方法上使用了fs.createWriteStream方法。 An example of this can be found at: enter link description here 可以在以下位置找到此示例: 在此处输入链接描述

This has taken away the need for me to actually request the images with the CORS headers as when they are stored locally, the headers are no longer required. 这使我无需实际使用CORS标头请求图像,因为它们在本地存储时,不再需要标头。 I can then save the base64 that is generated by my cropper directive and store this on amazon S3 easily. 然后我可以保存由我的cropper指令生成的base64,并将其存储在amazon S3上。

If the user navigates away before cropping the local images I delete them from the local folder so it doesn't get clogged up. 如果用户在裁剪本地图像之前导航,我会从本地文件夹中删除它们,这样它就不会被堵塞。

I hope this is of some help to those who are also having issues with the CORS headers - even though it's just a workaround. 我希望这对那些也遇到CORS标题问题的人有所帮助 - 尽管这只是一种解决方法。

Well I've seen this problem in a number of different forms: one is where you are serving a page in S3 that access a nodejs backend in either an EC2 or in Elastic Beanstalk. 我已经以多种不同的形式看到了这个问题:一个是你在S3中为一个页面提供服务,在EC2或Elastic Beanstalk中访问nodejs后端。

In one case it was the browser I was using IE10 that threw errors because the browser required Preflight options to be set. 在一个案例中,我使用IE10的浏览器会抛出错误,因为浏览器需要设置Preflight选项。

In the other cases I was using Restify in Elastic Beanstalk and Angular in S3. 在其他情况下,我在S3中使用Elastic Beanstalk和Angular中的Restify。 I added the Restify-cors middleware package to the request: 我在请求中添加了Restify-cors中间件包:

var corsMiddleWare = require('restify-cors-middleware'); //npm install this package
var cors = corsMiddleWare ({
    allowHeaders:['Authorization', 'API-Token', 'API-Token-Expiry']
 });
server.pre(cors.preflight);
server.use(cors.actual);
//rest of server definition

This seemed to work. 这似乎有效。 In the case of express there is the node package express-cors: 在快递的情况下,有节点包express-cors:

var cors = require('cors');
app.use(cors());

In either case the key is that all requests must have the headers set properly, hence we add them to middleware. 在任何一种情况下,关键是所有请求必须正确设置标头,因此我们将它们添加到中间件。 (app/server.use) How can I support cors when using restify (app / server.use) 使用restify时如何支持cors

Are you using vanilla node? 你在使用香草节点吗? In that case you need to add the headers on every request you make to s3. 在这种情况下,您需要在对s3发出的每个请求中添加标头。

This was definitely an issue with it being a cached response for me. 这绝对是一个问题,它对我来说是一个缓存的回应。 It seems to lose some of the headers in cache. 它似乎丢失了缓存中的一些标头。 I was able to get it to work 100% of the time by appending a random time parameter to the image name, as in the example below. 通过在图像名称后附加一个随机时间参数,我可以100%的时间让它工作,如下例所示。

img = new Image();
img.src = "https://s3.amazonaws.com/bucket/img.png?t=" + (new Date().getTime() / 1000);    
img.crossOrigin = "Anonymous";

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

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