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?
Related
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);
});
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");
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;
}
}
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.
Browser JS
'use strict';
window.onload = () => {
let form = document.getElementById('sign_up_form'),
username = form.elements[0],
password = form.elements[1],
confirm = form.elements[2],
email = form.elements[3],
errors = document.getElementById('sign_up_errors');
username.addEventListener('change', (e) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', '/validate_username');
xhr.send();
xhr.onreadystatechange = () => {
console.log(xhr.readyState);
if (xhr.readyState === 4) {
console.log(xhr.status);
if (xhr.status === 200) {
console.log('AJAX SUCCESS');
};
};
};
});
confirm.addEventListener('change', (e) => {
if (password.value != confirm.value) {
errors.children[1].innerHTML = 'Passwords do not match.';
} else {
errors.children[1].innerHTML = '';
};
});
form.addEventListener('submit', (e) => {
e.preventDefault();
let form_data = {
username: username.value,
password: password.value,
confirm: confirm.value,
email: email.value,
};
let xhr = new XMLHttpRequest();
xhr.open('POST', '/validate_signup');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(form_data));
});
}
Server
'use strict';
let app = require('koa')(),
serve = require('koa-static'),
router = require('koa-router')(),
parse = require('koa-bodyparser'),
mongo = require('koa-mongo'),
fs = require('co-fs');
app.use(serve(__dirname + '/public'));
app.use(mongo({
uri: ******,
max: 100,
min: 1,
timeout: 30000,
log: false
}));
app.use(parse());
app.use(router.routes());
router.post('/validate_username', function *(next) {
console.log('username:');
console.log(this.request.body);
});
router.post('/validate_signup', function *(next) {
console.log('signup:');
console.log(this.request.body);
this.mongo.collection('users').findOne({'username': this.request.body.username}, (err, doc) => {
console.log(doc);
});
});
app.listen(5000);
The AJAX 'POST' request gives the form_data to the server and I can check the database but consoles 404 error. The AJAX 'GET' request just throws a 404 error after achieving readyState 4. I think I am using the routes incorrectly or am missing something in my AJAX requests but I am new to Koa.js and pretty much green all around so any help will be appreciated.
JS:
'use strict';
window.onload = () => {
let form = document.getElementById('sign_up_form'),
username = form.elements[0],
password = form.elements[1],
confirm = form.elements[2],
email = form.elements[3],
errors = document.getElementById('sign_up_errors');
username.addEventListener('input', (e) => {
let data = {username: username.value};
let xhr = new XMLHttpRequest();
xhr.open('POST', '/sign_up/username');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = () => {
console.log(xhr.readyState);
if (xhr.readyState === 4 && xhr.status === 200) {
if (JSON.parse(xhr.responseText).username) {
console.log('unavailable');
} else {
console.log('available');
};
};
};
});
};
SERVER:
'use strict';
let router = require('koa-router')({
prefix: '/sign_up'
});
router.post('/username', function *(next) {
console.log('Checking username...');
yield new Promise((resolve, reject) => {
this.mongo.collection('users').findOne({'username': this.request.body.username}, (err, doc) => {
if (doc) {resolve(doc)}
else {reject()};
});
}).then((doc) => {
if (doc) {
console.log('Promise: ' + doc);
this.body = {username: false};
};
}).catch(() => {
console.log('Promise rejected.');
this.body = {username: true};
});
});
module.exports = router;