cannot handle net::ERR_CONNECTION_REFUSED in pure js - javascript

I use pure js(without JQuery) to send an XMLHttpRequest request to server.
var _xhr = new XMLHttpRequest();
_xhr.open(type, url);
_xhr.setRequestHeader('Content-Type', 'application/json');
_xhr.responseType = 'json';
_xhr.onload = function () {
if (_xhr.status === 200) {
var _json = _xhr.response;
if (typeof _json == 'string')
_json = JSON.parse(_json);
success(_json);
} else {
error(_xhr);
}
};
_xhr.onerror = function(){
console.log('fail');
};
try {
_xhr.send(_to_send);
} catch (e){
options.error(_xhr);
}
when i send a request it's fails(this is ok) and i get an error but I CANNON HANDLE IT. xhr.onerror prints message to console but i get OPTIONS url net::ERR_CONNECTION_REFUSED too. How can I avoid this message in console?
Also i use window.onerror to handle all error but i can not handle this OPTIONS url net::ERR_CONNECTION_REFUSED

This worked for me:
// Watch for net::ERR_CONNECTION_REFUSED and other oddities.
_xhr.onreadystatechange = function() {
if (_xhr.readyState == 4 && _xhr.status == 0) {
console.log('OH NO!');
}
};
This is not limited to just net::ERR_CONNECTION_REFUSED because other network errors (e.g. net::ERR_NETWORK_CHANGED, net::ERR_ADDRESS_UNREACHABLE, net::ERR_TIMED_OUT) may be "caught" this way. I am unable to locate these error messages within the _xhr object anywhere, so making a programmatic decision about which network error has specifically occurred won't be reliable.

There is no way around that error showing in console. Just as if you request a file that does't exist you get a 404 in console, regardless of if you handle the error or not.

Related

Identify fetch error as due to CORS issue

I'd like to tell if a resource load has failed due to a CORS error, as I'd like to then use a proxy I've set up on my server. I don't want to use my proxy unless absolutely necessary as quite a lot of extra data will be piped through it.
When I do:
fetch("https://some-resource-somewhere-that-a-user-has-provided")
.then(response => {
// do stuff with the response
}).catch((e) => {
// e === Error("TypeError: Failed to fetch")
});
The error is pretty unhelpful (on chrome at least), but there is big red text in the console giving me the information I need!
How do I tell that
TypeError: Failed to fetch
is a CORS issue, or some other load problem?
I came up with below solution:
var xhttp = new XMLHttpRequest();
xhttp.onerror = function () {
if (this.status === undefined || this.status === 0) {
console.log('error due to CORS issue');
} else {
console.log("** An error occurred during the transaction", this);
}
};
xhttp.open("GET", "https://stackoverflow.com", true);
xhttp.send();

Slim cropper works perfectly fine on my localhost, but gives a 403 forbidden error on server

I'm using slim cropper to upload avatar's on my codeigniter project , It works perfectly on my localhost but on the server , the ajax call to the php that does the image upload keeps giving a 403 forbidden error, below is the section of the code:
function send(url, data, progress, success, err) {
var xhr = new XMLHttpRequest();
if (progress) {
xhr.upload.addEventListener('progress', function (e) {
progress(e.loaded, e.total);
});
}
xhr.open('POST', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var text = xhr.responseText;
// if no data returned from server assume success
if (!text.length) {
success();
return;
}
// catch possible PHP content length problem
if (text.indexOf('Content-Length') !== -1) {
err('file-too-big');
return;
}
// if data returned it should be in suggested JSON format
var obj = null;
try {
obj = JSON.parse(xhr.responseText);
} catch (e) {}
success(obj || text);
} else if (xhr.readyState === 4) {
err('fail');
}
};
xhr.send(data);
}
From what I've read , providing a CSRF token might solve the problem, but the request is made from the same domain and I don't require that on my localhost. What could be the problem?

Youtube API v3 get the Channel ID of user that uploaded a certain video

I want to get the channel ID of a user that uploaded a certain YouTube video on javascript to after that comparing the channel id to see if it's in an array.
The thing is, I can't find exactly how to get that from javascript. I tried to get:
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=[Video ID]&key=[my key]
but it gives me JSON parsing error on every video.
Anyone knows how to do it exactly using YouTube API? Doesn't matter if I have to add an exteral script on the html part.
And, as an example of what I want to do, for this video:
https://www.youtube.com/watch?v=jNQXAC9IVRw
it should return 'UC4QobU6STFB0P71PMvOGN5A'.
Any idea on how to do it?
I took the Ajax code from youmightnotneedjquery.com and edited it a bit to make a getJSON utility function. This worked for me:
var API_KEY = 'YOUR_API_KEY'; // Replace this with your own key
getJSON(
'https://www.googleapis.com/youtube/v3/videos?part=snippet&id=jNQXAC9IVRw&key=' + API_KEY,
function (err, data) {
if (err) {
alert(err);
} else {
alert(data.items[0].snippet.channelId);
}
}
);
function getJSON(url, callback) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// We have the JSON, now we try to parse it
try {
var data = JSON.parse(request.responseText);
// It worked, no error (null)
return callback(null, data);
} catch(e) {
// A parsing arror occurred
console.error(e);
return callback('An error occurred while parsing the JSON.');
}
}
// If an error occurred while fetching the data
callback('An error occurred while fetching the JSON.');
};
request.onerror = function() {
// There was a connection error of some sort
callback('An error occurred while fetching the JSON.');
};
request.send();
}

Is it possible to return value from PHP to Ajax after error 500?

This Ajax is sending some data to php file and getting back the response that is showed in my html. Everything is working fine but sometimes I have been getting Error 500 response from php file. I know why and it is ok because as you can see after error 500 I'm calling the Ajax function again.
My question is. Is it possible to return from php file also some data after getting error 500? By data I mean variable returned from php file when the error occured.
function tr() {
var vysledok = document.getElementById('vysledok_body');
var text= document.getElementById('source').value;
var languageFrom = document.getElementById("src").value;
var languageTo = document.getElementById("dst").value;
vysledok.innerHTML="";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', "https://.... someurl.php?
from=" + languageFrom + "&to=" + languageTo + "&text=" + text, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var obj = JSON.parse(xmlhttp.responseText);
console.log(obj.ip);
vysledok.innerHTML = "<p class='bdr'>"+obj.text+"</p>";
}
if(xmlhttp.status == 500) {
//console.log('nejde');
tr();
}
}
};
xmlhttp.send(null);
}
That depends entirely on what is causing the error. What you can do is catching the error if it is caused by an exception and in the catch block handle it the way you want.
For example you can return a value in the catch block and set the response code to 500 from PHP.
If however your script crashes with a fatal error that is not handled you can't change the return value there, but could still configure your web server to deliver a custom error page that can be read by your JS.

Repeat failed XHR

Is there any common way, example or code template how to repeat a XHR that failed due to connection problems?
Preferably in jQuery but other ideas are welcome.
I need to send some application state data to a database server. This is initiated by the user clicking a button. If the XHR fails for some reason I need to make sure that the data is sent later (no interaction needed here) in the correct order (the user may press the button again).
Here's how I would do it:
function send(address, data) {
var retries = 5;
function makeReq() {
if(address == null)
throw "Error: File not defined."
var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
if(req == null)
throw "Error: XMLHttpRequest failed to initiate.";
req.onload = function() {
//Everything's peachy
console.log("Success!");
}
req.onerror = function() {
retries--;
if(retries > 0) {
console.log("Retrying...");
setTimeout(function(){makeReq()}, 1000);
} else {
//I tried and I tried, but it just wouldn't work!
console.log("No go Joe");
}
}
try {
req.open("POST", address, true);
req.send(data); //Send whatever here
} catch(e) {
throw "Error retrieving data file. Some browsers only accept cross-domain request with HTTP.";
}
}
makeReq();
}
send("somefile.php", "data");
To make sure everything is sent in the right order, you could tack on some ID variables to the send function. This would all happen server-side though.
And of course, there doesn't need to be a limit on retries.
jQuery provides an error callback in .ajax for this:
$.ajax({
url: 'your/url/here.php',
error: function(xhr, status, error) {
// The status returns a string, and error is the server error response.
// You want to check if there was a timeout:
if(status == 'timeout') {
$.ajax();
}
}
});
See the jQuery docs for more info.

Categories

Resources