Programing

XMLHttpRequest 상태 0 (responseText가 비어 있음)

lottogame 2020. 9. 1. 07:55
반응형

XMLHttpRequest 상태 0 (responseText가 비어 있음)


XMLHttpRequest로 데이터를 가져올 수 없습니다 (상태 0 및 responseText가 비어 있음) :

xmlhttp = new XMLHttpRequest ();
xmlhttp.open ( "GET", "http://www.w3schools.com/XML/cd_catalog.xml", true);
xmlhttp.onreadystatechange = function () 
{
  if (xmlhttp.readyState == 4)
    alert ( "상태"+ xmlhttp.status);
}
xmlhttp.send ();

"상태 0"을 경고합니다.

localhost 요청과 동일한 상황 (cd_catalog.xml이 로컬 파일로 저장 됨)

xmlhttp.open ( "GET", "http : //localhost/cd_catalog.xml", true);

그러나 localhost IP 요청으로

xmlhttp.open ( "GET", "http://127.0.0.1/cd_catalog.xml", true);

그리고 로컬 파일 요청으로

xmlhttp.open ( "GET", "cd_catalog.xml", true);

모든 것이 정상입니다 (상태 200).

온라인 요청에 문제 (상태 = 0)의 원인은 무엇입니까?

추신 : 라이브 HTTP 헤더는 4 가지 경우 모두 정상임을 보여줍니다.

  HTTP / 1.1 200 정상
  콘텐츠 길이 : 4742

PS2 : VMWare의 Apache 로컬 웹 서버 (호스트 OS Win7, 게스트 OS Ubuntu, 네트워크 어댑터 – NAT). 브라우저 – Firefox.


스크립트가 포함 된 html 파일이 파일 구성표를 통해 브라우저에서 열리면 상태가 0입니다. 서버 (apache 또는 tomcat 무엇이든)에 파일을 배치 한 다음 브라우저에서 http 프로토콜을 통해 엽니 다. (예 : http : //localhost/myfile.html ) 이것이 해결책입니다.


문제의 원인은 도메인 간 호출을 시도했지만 실패했기 때문 입니다.

localhost 개발을하고 있다면 도메인 간 호출을 할 수 있습니다. 저는 항상 그렇게합니다.

Firefox의 경우 구성 설정에서 활성화해야합니다.

signed.applets.codebase_principal_support = true

그런 다음 XHR 오픈 코드에 다음과 같이 추가합니다.

  if (isLocalHost()){
    if (typeof(netscape) != 'undefined' && typeof(netscape.security) != 'undefined'){
      netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
    }
  }

IE의 경우 내가 기억하는 것이 맞다면 "기타 → 도메인 간 데이터 소스 액세스"에서 브라우저의 보안 설정을 활성화하여 ActiveX XHR에서 작동하도록하는 것입니다.

IE8 이상에서는 네이티브 XmlHttpRequest 개체에 도메인 간 기능도 추가했지만 아직 이러한 기능을 사용하지는 않았습니다.


실제로 버튼 유형이 제출되지 않은 버튼인지 확인하십시오. 이로 인해 최근에 만난 상태 충돌이 발생했습니다.


서버가 OPTIONS 메소드에 응답하고 다음과 같은 헤더를 사용하여 GET 및 POST (사용중인 항목 중 하나)에 응답하는 경우 :

Access-Control-Allow-Origin: *

잘 작동 할 수 있습니다. FireFox 3.5 및 0.4.0에서 볼 수 있습니다. 분명히 그 헤더와 OPTIONS에 대한 초기 응답을 통해 서버는 브라우저에 "계속 진행하여이 도메인 간 요청을 통과 시키십시오"라고 말합니다.


요청 시간 제한 도 고려하십시오 .

최신 브라우저 는 서버 응답 전에 너무 많은 시간이 지나면 readyState = 4 및 s tatus = 0을 반환합니다.


setRequestHeader("Access-Control-Allow-Origin","*")서버 응답에 추가 하십시오.


비슷한 문제에 직면했습니다. 모든 것이 괜찮 았고 "준비 상태"는 4 였지만 "상태"는 0이었습니다. 아파치 PHP 포터블 서버를 사용하고 있었고 "XMLHttpRequest"객체를 사용한 파일이 html 파일 이었기 때문입니다. 파일 확장자를 php로 변경했는데 문제가 해결되었습니다.


Open javascript console. You'll see an error message there. In my case it was CORS.


To answer the question of why http://127.0.0.1/cd_catalog.xml works while http://localhost/cd_catalog.xml doesn't: Firefox is treating 127.0.0.1 and localhost as two different domains.


To see what the problem is, when you get the cryptic error 0 go to ... | More Tools | Developer Tools (Ctrl+Shift+I) in Chrome (on the page giving the error)

Read the red text in the log to get the true error message. If there is too much in there, right-click and Clear Console, then do your last request again.

My first problem was, I was passing in Authorization headers to my own cross-domain web service for the browser for the first time.

I already had:

Access-Control-Allow-Origin: *

But not:

Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization

in the response header of my web service.

After I added that, my error zero was gone from my own web server, as well as when running the index.html file locally without a web server, but was still giving errors in code pen.

Back to ... | More Tools | Developer Tools while getting the error in codepen, and there is clearly explained: codepen uses https, so I cannot make calls to http, as the security is lower.

I need to therefore host my web service on https.

Knowing how to get the true error message - priceless!


Here's another case in which status === 0, specific to uploading:

If you attach a 'load' event handler to XHR.upload, as suggested by MDN (scroll down to the upload part of 'Monitoring progress'), the XHR object will have status=0 and all the other properties will be empty strings. If you attach the 'load' handler directly to the XHR object, as you would when downloading content, you should be fine (given you're not running off localhost).

However, if you want to get good data in your 'progress' event handlers, you need to attach a handler to XHR.upload, not directly to the XHR object itself.

I've only tested this so far on Chrome OSX, so I'm not sure how much of the problem here is MDN's documentation and how much is Chrome's implementation...


Alex Robinson already (and first) gives the correct answer to this issue. But to elaborate it a little more...

You must add the HTTP response header:

Access-Control-Allow-Origin: *

If you do this, the result is not just 'might work', but 'will work'.

NB What you need to add is an HTTP response header - so you can only do this on a server which you control. It will never be possible to directly fetch http://w3schools.com/XML/cd_catalog.xml from its original URL using an XMLHttpRequest (as per OP's question), because that resource does not (at least, not as of 24 Apr 2015) include any such CORS header.

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing gives more info.


My problem similar to this was solved by checking my html code. I was having an onclick handler in my form submit button to a method. like this : onclick="sendFalconRequestWithHeaders()". This method in turn calls ajax just like yours, and does what I want. But not as expected, my browser was returning nothing.

Learned From someone's hardwork, I have returned false in this handler, and solved. Let me mention that before arriving to this post, I have spent a whole 3-day weekend and a half day in office writing code implementing CORS filters, jetty config, other jersey and embedded jetty related stuff - just to fix this., revolving all my understanding around cross domain ajax requests and standards stuff. It was ridiculous how simple mistakes in javascript make you dumb.

To be true, I have tried signed.applets.codebase_principal_support = true and written isLocalHost() **if**. may be this method needs to be implemented by us, firefox says there is no such Now I have to clean my code to submit git patch cleanly. Thanks to that someone.


A browser request "127.0.0.1/somefile.html" arrives unchanged to the local webserver, while "localhost/somefile.html" may arrive as "0:0:0:0:0:0:0:1/somefile.html" if IPv6 is supported. So the latter can be processed as going from a domain to another.


Alex Robinson and bmju provided valuable information to understand cross-origin issues. I wanted to add that you may need to make an explicit OPTIONS call in your client code before making the desired GET/POST (e.g. against a CORS OAuth service endpoint). Your browser/library may not automatically handle the OPTIONS request. Gruber, this is one of the possible answers to your question.


I had the same problem (readyState was 4 and status 0), then I followed a different approach explained in this tutorial: https://spring.io/guides/gs/consuming-rest-jquery/

He didn't use XMLHttpRequest at all, instead he used jquery $.ajax() method:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="hello.js"></script>
</head>

<body>
    <div>
        <p class="greeting-id">The ID is </p>
        <p class="greeting-content">The content is </p>
    </div>
</body>

and for the public/hello.js file (or you could insert it in the same HTML code directly):

$(document).ready(function() 
 {
    $.ajax({
        url: "http://rest-service.guides.spring.io/greeting"
   }).then(function(data) {
      $('.greeting-id').append(data.id);
      $('.greeting-content').append(data.content);
   });
 });

I had to add my current IP address (again) to the Atlas MongoDB whitelist and so got rid of the XMLHttpRequest status 0 error


I just had this issue because I used 0.0.0.0 as my server, changed it to localhost and it works.


Edit: Please read Malvolio's comments below as this answer's knowledge is outdated.

You cannot do cross-domain XMLHttpRequests.

The call to 127.0.0.1 works because your test page is located at 127.0.0.1, and the local test also works since, well... it's a local test.

The other two tests fail because JavaScript cannot communicate with a distant server through XMLHttpRequest.

You might instead consider either:

  • XMLHttp-request your own server to fetch your remote XML content for you (php script, for example)
  • Trying to use a service like GoogleAppEngine if you want to keep it full JavaScript.

Hope that helps

참고URL : https://stackoverflow.com/questions/5005960/xmlhttprequest-status-0-responsetext-is-empty

반응형