jQuery Post를 Google API로 보내는 Access-Control-Allow-Origin 오류
'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을 사용하는 방법을 모르겠습니다. Authorization 헤더를 추가해야하기 때문에 $ .ajax의 beforeCall 없이는 어떻게 해야할지 모르겠습니다.
이 어둠에 대한 빛이 있습니까?
이것이 코드입니다.
<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
});
I had exactly the same issue and it was not cross domain but the same domain. I just added this line to the php file which was handling the ajax request.
<?php header('Access-Control-Allow-Origin: *'); ?>
It worked like a charm. Thanks to the poster
If you have this error trying to consume a service that you can't add the header Access-Control-Allow-Origin *
in that application, but you can put in front of the server a reverse proxy, the error can avoided with a header rewrite.
Assuming the application is running on the port 8080 (public domain at www.mydomain.com), and you put the reverse proxy in the same host at port 80, this is the configuration for Nginx reverse proxy:
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 *;
}
}
Yes, the moment jQuery sees the URL belongs to a different domain, it assumes that call as a cross domain call, thus crossdomain:true
is not required here.
Also, important to note that you cannot make a synchronous call with $.ajax
if your URL belongs to a different domain (cross domain) or you are using JSONP. Only async calls are allowed.
Note: you can call the service synchronously if you specify the async:false
with your request.
In my case the sub domain name causes the problem. Here are details
I used app_development.something.com
, here underscore(_
) sub domain is creating CORS error. After changing app_development
to app-development
it works fine.
'Programing' 카테고리의 다른 글
추상 클래스 테스트 (0) | 2020.06.23 |
---|---|
Select Unique와 Select Distinct의 차이점 (0) | 2020.06.23 |
'명명 된 파이프 공급자, 오류 40-SQL Server에 대한 연결을 열 수 없습니다'오류를 어떻게 수정합니까? (0) | 2020.06.23 |
Mailto 링크는 Chrome에서 아무것도하지 않지만 Firefox에서는 작동합니까? (0) | 2020.06.23 |
Android 프로젝트에서 사용하지 않는 문자열을 찾는 간단한 방법이 있습니까? (0) | 2020.06.23 |