Hi All,
Is there a way to check if a resource exists using JS without getting 404?
I am unable to find any library which does this job. I am using clientside JS.
For example : I am using $.getJSON() but it does throw 404 in console logs, if its an invalid resource
Kindly let me know the best solution for the above issue.
Thanks in advance!
Solved! Go to Solution.
Views
Replies
Total Likes
Hi,
How about below 2 options?
HEAD
method instead of GET
method in your jQuery's ajax method. The HEAD
method will only retrieve the headers of the response, so it doesn't download the entire resource.XMLHttpRequest
object to make a HEAD
request and check the status
property of the XMLHttpRequest
object.var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://example.com/resource');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('Resource exists');
} else if (xhr.status === 404) {
console.log('Resource does not exist');
}
}
};
xhr.send();
Thanks,
Monendra
Please see this thread
When data is retrieved from remote servers (which is only possible using the script
or jsonp
data types), the error callbacks and global events will never be fired.
Hi,
How about below 2 options?
HEAD
method instead of GET
method in your jQuery's ajax method. The HEAD
method will only retrieve the headers of the response, so it doesn't download the entire resource.XMLHttpRequest
object to make a HEAD
request and check the status
property of the XMLHttpRequest
object.var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://example.com/resource');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('Resource exists');
} else if (xhr.status === 404) {
console.log('Resource does not exist');
}
}
};
xhr.send();
Thanks,
Monendra
Typically AEM public websites has the /content/my-site/home/jcr:content/root/container/componentA path blocked, because of security reasons by the dispatcher. The reason why you might be getting 404 is because during development, your session is set as admin:admin, while testing in dispatcher, the rules has restricted you to access such resource path from the JCR in AEM publisher.
Another option is, you can write a custom servlet that accepts a parameter. This parameter can be ?path for example. When this servlet is enabled, you can make your JS call your own servlet, and you can return JSON content-type, and 200 server status, and the text { status: true }. But you might want to watch out for brute force attacks where calling your servlet is going to spike the load of your AEM publishers.
Views
Likes
Replies