‘Access-Control-Allow-Origin’오류에 대해 많이 읽었지만 해결해야 할 사항을 이해하지 못합니다. (
Google 중재자 API를 사용하고 있는데 새 시리즈 를 추가 하려고하면 다음과 같은 메시지가 나타납니다.
XMLHttpRequest cannot load
https://www.googleapis.com/moderator/v1/series?key=[key]
&data%5Bdescription%5D=Share+and+rank+tips+for+eating+healthily+on+the+cheaps!
&data%5Bname%5D=Eating+Healthy+%26+Cheap
&data%5BvideoSubmissionAllowed%5D=false.
Origin [my_domain] is not allowed by Access-Control-Allow-Origin.
콜백 매개 변수를 사용하거나 사용하지 않고 ‘Access-Control-Allow-Origin *’를 헤더에 추가하려고했습니다. 승인 헤더를 추가해야하기 때문에 $ .getJSON을 사용하는 방법을 모르겠습니다.
이 어둠에 대한 빛이 있습니까?
이것이 코드입니다.
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
var scope = "https://www.googleapis.com/auth/moderator";
var token = '';
function create(){
if (token == '')
token = doCheck();
var myData = {
"data": {
"description": "Share and rank tips for eating healthily on the cheaps!",
"name": "Eating Healthy & Cheap",
"videoSubmissionAllowed": false
}
};
$.ajax({
url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
type: 'POST',
callback: '?',
data: myData,
datatype: 'application/json',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', token);
}
function doLogin(){
if (token == ''){
token = google.accounts.user.login(scope);
}else{
alert('already logged');
}
}
function doCheck(){
token = google.accounts.user.checkLogin(scope);
return token;
}
</script>
...
...
<div data-role="content">
<input type="button" value="Login" onclick="doLogin();">
<input type="button" value="Get data" onclick="getModerator();">
<input type="button" value="Create" onclick="create();">
</div><!-- /content -->
답변
dataType 매개 변수를 dataType : ‘jsonp’ 로 수정하고 crossDomain : true를 추가하는 Access-Control-Allow-Origin 오류를 해결했습니다 .
$.ajax({
url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
답변
나는 정확히 같은 문제가 있었고 도메인 간이 아니라 동일한 도메인이었습니다. 방금이 줄을 ajax 요청을 처리하는 php 파일에 추가했습니다.
<?php header('Access-Control-Allow-Origin: *'); ?>
그것은 매력처럼 작동했습니다. 포스터 덕분에
답변
이 Access-Control-Allow-Origin *
응용 프로그램 에서 헤더 를 추가 할 수없는 서비스를 사용하려고하는이 오류가 발생 하지만 서버 앞에 리버스 프록시를 넣을 수있는 경우 헤더를 다시 쓰면 오류를 피할 수 있습니다.
응용 프로그램이 포트 8080 (공용 도메인 www.mydomain.com ) 에서 실행 중이고 포트 80의 동일한 호스트에 리버스 프록시를 넣었다고 가정하면 다음은 Nginx 리버스 프록시 의 구성입니다 .
server {
listen 80;
server_name www.mydomain.com;
access_log /var/log/nginx/www.mydomain.com.access.log;
error_log /var/log/nginx/www.mydomain.com.error.log;
location / {
proxy_pass http://127.0.0.1:8080;
add_header Access-Control-Allow-Origin *;
}
}
답변
예, jQuery가 URL이 다른 도메인에 속하는 것을 본 순간,이 호출은 도메인 간 호출로 가정하므로 crossdomain:true
여기서는 필요하지 않습니다.
또한 $.ajax
URL이 다른 도메인 (크로스 도메인)에 속하거나 JSONP를 사용중인 경우 동기식 호출을 수행 할 수 없습니다 . 비동기 호출 만 허용됩니다.
참고 : async:false
요청과 함께 를 지정하면 서비스를 동 기적으로 호출 할 수 있습니다 .
답변
필자의 경우 하위 도메인 이름으로 인해 문제가 발생합니다. 자세한 내용은 다음과 같습니다
내가 사용 app_development.something.com
여기에 밑줄 (, _
) 서브 도메인이 CORS 오류를 만드는 것입니다. 변경 한 후에 app_development
에 app-development
그것을 잘 작동합니다.
답변
PHP에는 약간의 해킹이 있습니다. 또한 Google뿐만 아니라 귀하가 제어하거나 액세스 제어-허용-오리진을 추가 할 수없는 모든 웹 사이트에서 작동합니다 *
웹 서버에서 PHP 파일 (예 : getContentFromUrl.php )을 생성하고 약간의 트릭을 만들어야합니다.
PHP
<?php
$ext_url = $_POST['ext_url'];
echo file_get_contents($ext_url);
?>
JS
$.ajax({
method: 'POST',
url: 'getContentFromUrl.php', // link to your PHP file
data: {
// url where our server will send request which can't be done by AJAX
'ext_url': '/programming/6114436/access-control-allow-origin-error-sending-a-jquery-post-to-google-apis'
},
success: function(data) {
// we can find any data on external url, cause we've got all page
var $h1 = $(data).find('h1').html();
$('h1').val($h1);
},
error:function() {
console.log('Error');
}
});
작동 방식 :
- JS의 도움으로 브라우저가 서버에 요청을 보냅니다.
- 서버는 다른 서버로 요청을 보내고 다른 서버 (모든 웹 사이트)에서 응답을받습니다.
- 귀하의 서버는이 회신을 JS로 보냅니다.
그리고 우리는 onClick 이벤트를 만들 수 있습니다. 이것이 도움이되기를 바랍니다!