friedman
friedman

Reputation: 675

jQuery Ajax GET request returns 500 error in some cases

What would be the reason of receiving 500 internal server error after trying to load some pages with JS (jQuery) ajax?

Please do the console test on https://beerservice.pl/ When I try to GET:

$.ajax({
type: "GET",
url: "/",
dataType: "html",
error: function(e) {
    console.log(JSON.stringify(e));
} });

or some static page:

$.ajax({
type: "GET",
url: "https://beerservice.pl/pl/i/Kontakt/15",
dataType: "html",
error: function(e) {
    console.log(JSON.stringify(e));
} });

everything is ok, I receive code 200 and the full HTML in response. But when I try to GET a product page which normally works in browser, like:

$.ajax({
type: "GET",
url: "https://beerservice.pl/pl/p/Pegas-NovoTap-/343",
dataType: "html",
error: function(e) {
    console.log(JSON.stringify(e));
} });

then I receive 500 error. I can't see the point. Unfortunately this is SaaS software and the developer doesn't provide the support for this.

Upvotes: 0

Views: 94

Answers (1)

piraces
piraces

Reputation: 1348

Looks like a CORS problem, executing the last ajax call from my browser gives me the following error:

Access to XMLHttpRequest at 'https://beerservice.pl/pl/p/Pegas-NovoTap-/343' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

So the page has an Access-Control-Allow-Origin header that makes the request fail. Nevertheless you can use a custom proxy or one of the free proxies online that avoids that CORS restrictions.

Please take a look at the snippet below, it uses allorigins.win to proxy the request to the desired page.

There is plenty of proxies like this online for free: https://gist.github.com/jimmywarting/ac1be6ea0297c16c477e17f8fbe51347

I would recommend you to go with a custom proxy instead of trusting someone else one.

$.getJSON('https://api.allorigins.win/get?url=' + encodeURIComponent('https://beerservice.pl/pl/p/Pegas-NovoTap-/343') + '&callback=?', function(data){
	alert(data.contents);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions