Catching an Access-Control-Allow-Origin error in JavaScript - javascript

I wrote a function that keeps returning an Access-Control-Allow-Origin error. This is actually fine for me; I don't want to fix this. I just want to catch it so I can read its message in my program.
All the code that causes the error to be thrown is within my try block, and my catch block displays the error's string message. However, when I run the code, no error is caught, and the error shows up in red in the console. How do I catch this error and store its message?
try {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (this.status < 400 && this.status >= 300) {
console.log('this redirects to ' + this.getResponseHeader("Location"));
} else {
console.log('doesn\'t redirect');
}
}
xhr.open('HEAD', $scope.suggLink, true);
xhr.send();
} catch(e) {
console.log('Caught it!');
console.log(e.message);
}

While browsers will log a more-detailed error message to the console, you can’t access that from your code. See https://bugs.chromium.org/p/chromium/issues/detail?id=118096#c5:
The details of errors of XHRs and Fetch API are not exposed to JavaScript for security reasons.
As far as the what specs actually require here, the Fetch spec is what defines the details of the “status message” to provide in case of an error — even if XHR is used instead of the Fetch API (the XHR spec references the Fetch spec). And for any network error or response blocked by the browser, the Fetch spec requires that the status message be “the empty byte sequence”:
A network error is a response whose status is always 0, status message is always the empty byte sequence, header list is always empty, body is always null, and trailer is always empty.
So all you can get back from any error you can catch is “TypeError: Failed to fetch” or such.
If you’re using XHR, all you have for handling an error is the onerror event handler:
xhr.onerror = function() { console.log("Error occurred but I dunno what exactly.")}

jquery version of above (sideshowbarker's) workaround for CORS error:
let sURL = 'https://www.mocky.io/v2/5185415ba171ea3a00704eed';
$.getJSON(sURL, function (json)
{
console.log('json from web-service ->', json);
})
.fail(function()
{
console.log("error - could not get json data from service");
});

Related

How to send an error message from the server to the client using django and print it to the console?

I have a server request that is supposed to find a file, if it doesn't find that file, in need to print in the js console a custom message saying "I couldn't find file x".
I have tried raising exceptions, raising Http errors, sending custom requests....
But I have no idea how to send both an error (e.g 400, 404...) and a custom message associated with that error.
The purpose of this is, when the XMLHttpRequest() object gets a response, if the status isn't 200, that;s when the error ought to be printed.
I have no interest as to whether this is good practice or not, I just need to be able to do it somehow.
On the server side I am attempting something along the lines of:
raise HttpResponse('I am message')
On the client side I am attempting:
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onloadend = () => {
if (xhr.status != 200) {
//print error somehow
}
}
If you anticipate an error occurring in your back end you can wrap that code in a try catch block and instead of throwing an error you can just get the text from that the error is and send that back. That will result in a 200 response though since you caught the error. So id responded with some sort of object where one of the properties is the status. Something like:
[
['status'] => 'error',
['message'] => 'I've fallen and cant get up'
]
Then you can just:
if(response.data.status == 'error') {
console.log(response.data.message);
}
Hope that helps.

How to use the Fetch API cross-origin to load text or JSON data in Javascript?

First of all, I was using this (maybe old) code in Javascript:
function GetJson(url)
{
// 1. New Object XMLHttpRequest
var xhr = new XMLHttpRequest();
// 2. Config it
xhr.open('GET', url, false);
// 3. Send request
xhr.send();
// 4. Errors
if (xhr.status != 200) {
// Responce error out
return( xhr.status + ': ' + xhr.statusText ); // 404: Not Found
} else {
// Responce result
return( xhr.responseText ); // responseText --
}
}
This code solved the problem. Until this URL came:
https://bittrex.com/api/v1.1/public/getmarketsummaries/
The first error I encountered is:
XMLHttpRequest can not load
https://bittrex.com/api/v1.1/public/getmarketsummaries/. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'file: //' is therefore not allowed access.
To not change anything in the browser, long searches have led me to the fetch() function. But I categorically cannot understand how to get a response from the server in the form of JSON or at least in the form of text (for further conversion to JSON)
I try this:
fetch('https://bittrex.com/api/v1.1/public/getmarketsummaries/',{mode:'no-cors'})
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
And I get the answer:
Looks like there was a problem. Status Code: 0
Is there any way to get the data? It is desirable in a variable. Because I just do not understand how fetch works.
I just need to get data from the API for further processing.
You still have problem with cors. Mode "no-cors" just does not work as you expecting.
What you're dealing with is Cross-Origin Resource Sharing (CORS). The URL you're requesting the data from doesn't allow the data to be fetched from another domain. The reason your second snippet works is because you set the mode to no-cors. The call will succeed but your code won't be able to access any of the data. It is kinda useless for your purpose.

xmlHttpRequest.onerror handler use case

What sort of situations could cause this handler to be called? I'm not finding any instance where this method throws an error.
I tried with the device offline, I get xmlHttpRequest.status = 0 but no error.
Question is what sort of situations can I create in order to test functionality of this handler.
var xmlhttp = new XMLHttpRequest(),
method = 'GET',
url = 'https://developer.mozilla.org/';
xmlhttp.open(method, url, true);
xmlhttp.onerror = function () {
console.log("** An error occurred during the transaction");
};
xmlhttp.send();
From: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onerror
Your question is the perfect example. Just try your code from your web developer console while on this very page.
Here, try it yourself:
var xmlhttp = new XMLHttpRequest(),
method = 'GET',
url = 'https://developer.mozilla.org/';
xmlhttp.open(method, url, true);
xmlhttp.onerror = function () {
console.log("** An error occurred during the transaction");
};
xmlhttp.send();
When dealing with any network based IO all kinds of things could happen. Cross-Origin requests are only one. What if the server is offline, DNS lookup fails, a router between you and the server that is critical point of failure goes down?
Since an XHR call is for a server response, onerror would come into play when there is an error at the server. Changing your client to be offline doesn't simulate a server error.
Suppose the server resource gets moved and the server responds with a 404 error? What if the server times out? What if the request itself is malformed and causes the server to throw an error?

How do you handle an "Access to restricted URI denied" error in JavaScript when using XMLHttpRequest?

I have the following code:
var req = new XMLHttpRequest();
req.onload = function(){
if (req.status === "200"){
doSomethingWithTheReceivedData();
}
else {
alert("Error msg");
}
};
However when running index.html directly from my computer (when it isn't being served from my server) I get "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied" in the Firefox web console of course because the relative path that the script is trying to access isn't available on my computer (it is on my server).
Now I want to handle this error correctly, because currently when a user clicks the button that triggers this code nothing happens. I already added the status code check, but that doesn't seem to work for handling this error, I assume a request is never returned? So how do I handle such an error?
Use a try-catch when you send the request:
try{
req.send(null);
}catch(e){
alert(e.message);
}

Load error is not captured by try catch block

I have a code like:
try{
...
} catch(error){
...
};
In try block, there is a function call that makes a request to a server. When there is no resource on the server, an error is raised (as I can see in Google Chrome's developers tool):
Failed to load resource: the server responded with a status of 404 (Not Found)
and I am trying to catch it in the catch block, but the error is not captured.
Is it a feature of JavaScript that load error is not captured by try catch block?
Typically, when requesting information from a server (for instance, via ajax, by setting the src of an img element, etc.), you don't get an exception, but you do get an error event or callback, not least because the code doing the request finishes before the request does, so it's impossible to throw an exception at that point. Since you haven't shown how you're requesting the information, it's impossible to be more specific, but this is why you're not getting an exception.
For instance, with an ajax request, if there's an error you see the ajax request complete but with the statusCode of the XMLHttpRequest object being an error status code, rather than 200. E.g.:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
// The request is complete; did it work?
if (xhr.statusCode >= 200 && xhr.statusCode < 300) {
// Yes
}
else {
// No, got a code outside the 2xx range
}
}
};
xhr.open("GET", "/your/url/here", true);
xhr.send();

Categories

Resources