Where to add CORS headers in AWS EC2

北城余情 提交于 2019-12-08 12:20:59

问题


I'm making a POST request from a browser to my EC2 AWS server but getting the following error back.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.example.com' is therefore not allowed access. The response had HTTP status code 401.

I've done some research and release I need to enable CORS on my EC2 AWS server - I understand that I should be adding something along the lines of

<CORSConfiguration>
    <CORSRule>
    <AllowedOrigin>http://www.example1.com</AllowedOrigin>

    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
     <AllowedOrigin>http://www.example2.com</AllowedOrigin>

     <AllowedMethod>PUT</AllowedMethod>
     <AllowedMethod>POST</AllowedMethod>
     <AllowedMethod>DELETE</AllowedMethod>

     <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>

from AWS docs: AWS EC2 CORS

However I'm unsure of where I actually need to add this too. My AWS server knowledge it limited.

It's a Neo4j db and the call is:

getRequest = function () {
    $.ajax({
        url: 'http://exampleEC2:port/',
        type: 'POST',
        dataType: 'JSON',
        contentType: 'application/json;charset=UTF-8',
        password: 'xxxxxx',
        username: 'xxxx',
        data: dataObject,
        success: function (data) {
            console.log("success");
        },
        error: function(error) {
            console.log(error);
        }
    });
};

回答1:


You can add the CORS condition to your EC2 instance on the server itself. Assuming that this is an Apache EC2 instance, you can edit your .htaccess file to allow any domain or one specific domain:

Header set Access-Control-Allow-Origin "*"

or

Header set Access-Control-Allow-Origin "yourexternaldomain.tld"

If I remember correctly, CORS can only have one domain associated with it.

I did find someone had come up with a conditional declaration in the .htaccess file so that a couple different and specific domains could be allowed access:

Stackoverflow: Access-Control-Allow-Origin Multiple Origin Domains?




回答2:


I spent hours wrestling with this. Tried .htaccess. Tried .conf. Fooling around with firewalls.

In the end it was a single line of php:

header('Access-Control-Allow-Origin: *');



来源:https://stackoverflow.com/questions/39835982/where-to-add-cors-headers-in-aws-ec2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!