jQuery xml error 'No'Access-Control-Allow-Origin 'header is present on the request resource.'
http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml 에있는 xml 파일을 읽고 xml 을 파싱하고 싶은 곳에서 재미를 위해이 개인 프로젝트를 진행 하고 있습니다. 이를 사용하여 통화 간의 값을 변환하십시오.
지금까지 XML을 읽기 위해 매우 기본적인 코드를 작성했지만 다음과 같은 오류가 발생합니다.
XMLHttpRequest가 ****를로드 할 수 없습니다. 요청 된 리소스에 'Access-Control-Allow-Origin'헤더가 없습니다. 따라서 원본 ' http://run.jsbin.com '은 액세스가 허용되지 않습니다.
$(document).ready(
function() {
$.ajax({
type: 'GET',
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
dataType: 'xml',
success: function(xml){
alert('aaa');
}
});
}
);
나는 내 코드에서 잘못된 것이 보이지 않으므로 누군가가 내 코드에서 내가 뭘 잘못하고 있는지 그리고 어떻게 고칠 수 있는지 지적 할 수 있기를 바랍니다.
동일 출처 정책 으로 인해 http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
배포 된 파일에서에 대한 ajax 호출을 할 수 없습니다 .http://run.jsbin.com
소스 (일명 원본 ) 페이지와 대상 URL이 서로 다른 도메인 ( run.jsbin.com
및 www.ecb.europa.eu
)에 있으므로 코드는 실제로 일반 .이 아닌 교차 도메인 (CORS) 요청을 시도합니다 GET
.
간단히 말해서, 동일 출처 정책에 따르면 브라우저는 HTML 페이지 의 동일한 도메인 에있는 서비스에 대한 ajax 호출 만 허용해야 합니다.
예:
에서의 페이지 http://www.example.com/myPage.html
수는 직접에있는 서비스 요청 http://www.example.com
등을 http://www.example.com/api/myService
. 서비스가 다른 도메인 (예 :)에서 호스팅되는 경우 http://www.ok.com/api/myService
브라우저는 예상대로 직접 호출하지 않습니다. 대신 CORS 요청을 시도합니다.
간단히 말해서, 여러 도메인에서 (CORS) 요청 *을 수행하려면 브라우저에서 다음을 수행하십시오.
Origin
원래 요청에 헤더를 포함하고 (페이지의 도메인을 값으로 사용) 평소대로 수행합니다. 그리고- 경우에만 서버 응답 이 요청이 포함 (적절한 헤더
Access-Control-Allow-Origin
입니다 하나 그들 중 ) CORS 요청 수, 찾아보기는 전화 (거의 ** HTML 페이지가 같은 도메인에 있었던 경우는 것 정확히 방법)을 완료합니다.- If the expected headers don't come, the browser simply gives up (like it did to you).
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers
header.
How to fix it?
Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com
it will only make regular calls to www.example.com
! Other URLs, such as api.example.com
or even example.com
or www.example.com:8080
are considered different domains by the browser! Yes, if the port is different, then it is a different domain!
Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin
) to the server's responses. (Each server/language has a way to do that - check some solutions here.)
Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit: If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
'code' 카테고리의 다른 글
목록의 버튼으로 Listactivity에서 onListItemClick을 실행하는 방법은 무엇입니까? (0) | 2020.09.07 |
---|---|
C #에서 "var"는 무엇을 의미합니까? (0) | 2020.09.07 |
ggplot2에서 색상을 채우기 위해 텍스처를 추가하는 방법 (0) | 2020.09.07 |
Firefox에서 도메인 간 웹 보안 비활성화 (0) | 2020.09.06 |
세로 헤더가있는 HTML 테이블을 작성하는 가장 일반적인 방법은 무엇입니까? (0) | 2020.09.06 |