I need to send a get request to a company internal website on client side. Here is my code:
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script type='text/javascript'>
$(document).ready(function () {
var url = 'https://jsonplaceholder.typicode.com/photos'; //working
//var url = 'xxxxxxx'; //internal url (returns json), not working
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true)
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
console.log(xhr.response)
console.log(xhr.responseText)
}
}
xhr.send()
})
</script>
</head>
This works fine with a test url that I put in (of course, having different domain than my server), meaning that it works fine with CORS request.
However, it doesn't work with the internal company url. The error I got is “No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'abc'(my server) is therefore not allowed access.”
My question: What caused the error? Why my CORS request works with one website but not the other? Is there some restrictions on my company's internal website, e.g. my server is not whitelisted on its "origin firewall"?
Interesting enough, it works (i.e. I'm able to get the json response) if I use ajax and set dataType to jsonp. But of course, because the returned data is json not jsonp, I got a different error saying "unexpected token :". This made me to doubt myself. If it was something placed by the internal website, why does ajax/jsonp trick work?
The ajax code below works - it got valid json response. However, because the returned data is json not jsonp, I got a different error (as I expeted).
$.ajax({
url: 'xxxxxxx', //internal url (returns json)
dataType: 'jsonp',
success: function( response ) {
console.log( response ); // server response
}
});