简体   繁体   中英

Simple GET rest service works in IE only ( or Postman ) , but not in Chrome , not in Firefox

I have this HTML/bootstrap code ( actually button and "demo" placer ) :

<button type="button"  class="btn btn-primary" 
onclick="displayAll()">Show/Refresh Storage list</button>
<br/>
<p id="demo"></p>

It calls to this JavaScript piece of code :

function displayAll() {
var xmlhttp = new XMLHttpRequest();
var URL1 = 
"http://localhost:8080/MyStore/rest/StoreService/discslist";
URL1 += "?dummy="+  Math.random();
xmlhttp.open("GET",URL1, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() 
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        var discsList = JSON.parse(xmlhttp.responseText);
        myFunction(discsList);
    }
}   
}
function myFunction(atr) {
var txt="";
txt += "<table border='1' class='table table-striped'>"
txt += "<thead><tr><th>id</th><th>Disc Name</th><th>Quantity</th>
<th>price</th></tr></thead>"
    for (x in atr) {
        txt += "<tr><td>" + atr[x].id + "</td>";
        txt += "<td>" + atr[x].name + "</td>";
        txt += "<td>" + atr[x].qnty + "</td>";
        txt += "<td>" + atr[x].price + " $</td></tr>";
    }
    txt += "</table>" 
    document.getElementById("demo").innerHTML = txt;}

So the main idea is to display data returned from Rest service as a table and this is works fine in IE ( BTW , the postman works fine too and i can see the JSON output ) , but in Chrome and Firefox it does not .

During my investigation i found out that onreadystatechange event fires 3 times in IE and only on third time it comes with 4 and 200. In Chrome it fires once , in Firefox twice , but in both cases no 4/200 is sent back from Tomcat. ( Server is Tomcat 8.5. )

Anybody have an idea how to proceed from here and what could be an issue ?

Thanks

Well ,I have found the problem. It is actually related to CORS ( Cross-Origin Resource Sharing ) . I just added CORS filter to web.xml of my application And it works great. This is how to : https://enable-cors.org/server_tomcat.html

Regarding IE why this worked without this : As far as i understand This is because i open html file from my Desktop so IE work in "TRUST ZONE" so no CORS is applied on GET requests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM