xhr timeout gives invalid state error in ie11 - javascript

Am trying to set timeout in XMLHttpRequest but it shows invalid state error, here's the code
function get(url, options) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
// headers
if (options && options.headers) {
for (let header in options.headers) {
if (options.headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, options.headers[header]);
}
}
}
xhr.open('GET', url);
// FIXME: Why is IE11 failing on "xhr.timeout?
// xhr.timeout = 10000;
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
try {
const data = JSON.parse(xhr.responseText);
resolve(data);
} catch (ex) {
reject({
status: this.status,
statusText: xhr.statusText
});
}
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.ontimeout = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
export default { get };
I had a look at following links link1 link2 link3 and specifically kept xhr.timeout between xhr.open and xhr.send
I even tried this
xhr.onreadystatechange = function () {
if(xhr.readyState == 1 ) {
xhr.timeout = 5000;
}
};
But no luck

Add xhr.timeout after the xhr.open method.

You should set xhr.timeout only when you call xhr.open() in asynchronous mode, otherwise MSIE will rise an exception INVALID_STATE_ERR.
Example:
xhr.open("POST", url, true);
ps. Strangely, i don't see this issue in FF & Chrome.

Related

Getting returned value from another javascript file using async

class monitor {
constructor(){
this.delay = config.delay
delay(time) {
return new Promise(function (resolve) {
setTimeout(resolve, time);
});
}
async redacted (pid) {
if (this.err === true) {
await this.delay(this.delay)
}
console.log("MONITOR > Getting Item Attrs")
const options = {
method: 'get',
url: url + pid + '.json',
headers: {
accept: '*/*',
'accept-encoding': 'gzip, deflate, br',
},
proxy: this.proxy
}
return req(options)
.then((res) => {
//console.log(res)
let variants = res.data.skus
//console.log(variants)
const att = []
for (let [key, value] of Object.entries(variants)) {
if(value.inStock) att.push(key)
}
if(att.length >= 1){
console("MONITOR > Sourced Item")
return att;
} else {
("MONITOR > No Variants Available")
this.oos = true
this.redacted(config.pid);
}
})
.catch((err) => {
if (err?.response?.status == 403) {
console.error("MONITOR > Proxy Block # GET PRODUCT")
this.err = true
this.redacted(config.pid);
}
})
}
}
var hello = new monitor().redacted(config.pid);
console.log(hello)
From what I understand I need to wait for the promise to finish before returning but I am confused on how to execute this with my code and also call this file and store the return value in another file. I'm not sure if my formatting is wrong as well, but I tried changing and no fix anyways
This snippet isn't using asynch but, it gives you the idea. You need to await or .then the promise (the fetch/request). You first fetch the remote JSON file then you parse it / read it. Something like:
function getJSON(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
//xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(JSON.parse(xhr.response)); // <---------------
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON(primaryURL).then(function (res) {
if (res) {
//do something
} else {
console.log("response not found");
}
}).catch(function (error) {
console.log("Error getting document:", error);
});

The .net core mvc is reaching the json controller I POST, but I can't read it. I also get error code 415 when I use [FromBody]

I'm posting a data with XHR in the project I'm coding. A JSON reaches the Controller but if I use [FromBody] I get error code 415. If I don't use it, the incoming JSON looks empty.
Controller
[HttpPost]
[IgnoreAntiforgeryToken]
[Route("revizedCategoryzfc")]
public void revizedCategoryzfc([FromBody] Category model)
{
if (model.fileCode != null)
{
System.Console.WriteLine(model.fileCode);
}
System.Console.WriteLine("Girdi");
}
Post XHR Code
async function makeRequest(method, url, model) {
return new Promise(function(resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function() {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
}else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function() {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send(model);
});
}
document.querySelector('.save-service').addEventListener('click', async () => {
for (var es of document.querySelectorAll('.category-item'))
{
await makeRequest('POST', '/zfc/revizedCategoryzfc', JSON.stringify({
"Name": es.querySelector('.service-name').value,
"fileCode": es.querySelector('.filecodas').value,
"CategoryId": es.querySelector('.zfc-id').value
}))
}
})
Error
Since you user json strngify and frombody, you have to add this header to your xhr
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

Outer function being called before xmlhttprequest being done

room.onPlayerChat is an outer event i have no control on it, When i try to use it i need to process something on message and checking player role through xmlhttprequest and wait for response then send message to room chat but it doesn't wait for it(xmlhttprequest) to return the player's role and send the normal message (normal player role), how to hang that outer event (room.onPlayerChat) and its needed to handle any room chat source.
const makeRequest = (method, url, data = {}) => {
const xhr = new XMLHttpRequest();
return new Promise(resolve => {
xhr.open(method, url, true);
xhr.onload = () => resolve({
status: xhr.status,
response: xhr.responseText
});
xhr.onerror = () => resolve({
status: xhr.status,
response: xhr.responseText
});
if (method != 'GET') xhr.setRequestHeader('Content-Type', 'application/json');
data != {} ? xhr.send(JSON.stringify(data)) : xhr.send();
})
}
room.onPlayerChat = async function (player,message) {
let request = await makeRequest("GET", 'URL/TO/CHECK/PLAYER/ADMIN/ROLE' + player.name);
if (request.response == "YES")
{
room.sendmessage("ADMIN" + player.name + message);
return false;
}
}

Get status code from any website

I'd like to ensure that a url sent to my server is an actual website (heroku app) rather than validating for htp://fooxbvgf5766.herokuapp.com. A status code of 200 would tell me that url is an actual website.
Been searching and found this.
checkValidWebsite(appName) {
const url = `https://${appName}.herokuapp.com`
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
Running the function:
checkValidWebsite('foo')
.then(resp => {
console.log(resp)
})
.catch(e => {
console.log('Error:', e)
})
Checking for https://foo.herokuapp.com I get cors errors. Is there a way to detect that a url is an actual website?

TypeError: callback is not a function when downloading a Google Drive File

Im using the code from this example
https://gist.github.com/Daniel15/5994054
The picker returns a file and when i try to download it with this function
function downloadFile(file, callback) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
} else {
callback(null);
}
}
It throws this error
TypeError: callback is not a function callback(null) filepicker.js(line 130)
So from your example call
function initPicker() {
var picker = new FilePicker({
apiKey: 'AIzaSyB8a8yohsAyEz1eZEFgt2YE-tMgACYWnVs',
clientId: 458068379722,
buttonEl: document.getElementById('pick'),
onSelect: function(file) {
console.log(file);
downloadFile(file);
alert('Selected ' + file.title);
}
});
}
you are not passing a callback function, either handle this by checking callback is a function in the downloadFile method before it tries to run it.....
function downloadFile(file, callback) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
if (typeof callback == "function") {
callback(xhr.responseText);
}
};
xhr.onerror = function() {
if (typeof callback == "function") {
callback(null);
}
};
xhr.send();
} else {
if (typeof callback == "function") {
callback(null);
}
}
}
or provide a callback function.
function initPicker() {
var picker = new FilePicker({
apiKey: 'AIzaSyB8a8yohsAyEz1eZEFgt2YE-tMgACYWnVs',
clientId: 458068379722,
buttonEl: document.getElementById('pick'),
onSelect: function(file) {
console.log(file);
downloadFile(file, function(){
//do something when the file is donwloaded
});
alert('Selected ' + file.title);
}
});
}

Categories

Resources