问题
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