为此,我已尽力使用 stackoverflow 上已有的答案,但自 2 天以来一直没有成功。我想要做的是访问存储在亚马逊 Ec2 实例中的 Mp4 视频。这导致
XMLHttpRequest 无法加载请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“ http://localhost:8080 ”。响应具有 HTTP 状态代码 405。
我的 ngnix.conf 有像这样的标题
http{
............
server{
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
}
}
我的客户端 javascript 代码很简单,如下所示:
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
xhr.setRequestHeader('Access-Control-Allow-Methods', "HEAD, GET, POST, PUT, DELETE, OPTIONS");
xhr.setRequestHeader('Content-type', 'text/plain');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = <videoURL> ;
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
};
xhr.onerror = function() {
// Error code goes here.
};
xhr.send();