Can't get weather API - javascript

I am trying to get JSON data from openweathermap.org, but $.getJSON doesn`t work.
If I call API from browser it display JSON data, but it doesnt work in JS file.
$(document).ready(function(){
$("#button").click(function(){
navigator.geolocation.getCurrentPosition(location,error,{timeout:10000});
});
function location(pos){
$("#crd").html("Location: " + pos.coords.latitude + " , " + pos.coords.longitude);
$.getJSON("api.openweathermap.org/data/2.5/weather?lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&APPID=key", function(json){
$("#weather").html(JSON.stringify(json));
});
}
function error(err){
var errorCode = "";
switch(err.code) {
case err.PERMISSION_DENIED:
errorCode = "User denied the request for Geolocation.";
break;
case err.POSITION_UNAVAILABLE:
errorCode = "Location information is unavailable.";
break;
case err.TIMEOUT:
errorCode = "The request to get user location timed out.";
break;
case err.UNKNOWN_ERROR:
errorCode = "An unknown error occurred.";
break;
}
$("#crd").html("Error " + err.code + ": " + errorCode);
}
});
One more problem. It worked on localhost when I add http://, but it doesn`t work in codepen. Any idea?
I found solution that in codepen you need to use some cross-origin like https://cors-anywhere.herokuapp.com/

You are missed the sheme: http:// try with this:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&APPID=key", function(json){
$("#weather").html(JSON.stringify(json));
});

Related

Link Multiple accounts in Firebase

I have been stuck with this problem for a long time and i decided to post my problem here.
My problem is to merge the accounts (Facebook and Google) in Firebase. Independently sign-up with either one of them works fine.
At first when the user Sign-up with google and later with Facebook (that has the same email address with google) it throws and error. I managed to handle the error as you see on my code below but i don't know how to merge both accounts.
Here is what i have done so far:
facebookSignin: function() {
var self = this
firebase.auth().signInWithPopup(facebookProvider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
self.registerProfile()
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log("ERROR:" + error)
console.log("email is : " + error.email)
if (errorCode == 'auth/account-exists-with-different-credential') {
firebase.auth().fetchProvidersForEmail(error.email).then(providers => {
//providers returns this array -> ["google.com"]
console.log("Providers:" + providers)
console.log("Credential: " + JSON.stringify(error.credential))
firebase.auth().currentUser.link(error.credential).then(function(user) {
console.log("Account linking success", user);
});
}).catch(function(error){
console.log("error:" + error)
})
}
console.log("error code:" + error.code+ "error msg:" + error.message)
});
First i already Signed up with google
Now i want to login with Facebook with the same email address
I get the current-user null obviously because the user is not signed in, this is the error: error:TypeError: __WEBPACK_IMPORTED_MODULE_1_firebase___default.a.auth(...).currentUser is null .
I read the documentation about the merge part but still could not figure this out. https://firebase.google.com/docs/auth/web/account-linking#link-federated-auth-provider-credentials-to-a-user-account
I really appreciate the help.
After you fetchProvidersForEmail and figure out the existing Google user, you have to first login to that existing account:
firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider().setCustomParameters({login_hint: error.email})...
After that completes, you then:
firebase.auth().currentUser.linkWithCredential(error.credential)
So the user first has to verify ownership of the existing account before linking the Facebook account.

sapui5 - javascript error handling - without try-catch in every callback

I am developing a SAPUI5-App. Is there a way to show all errors directly to the customer without having to put a try-catch-block into every callback of sapui5? He will use my app in a mobile device and wouldn´t be able to see the log.
I tried already the following code:
<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
return false; //true = suppress error alert
};
window.addEventListener("error", handleError, true);
function handleError(evt) {
if (evt.message) {
alert("error: "+evt.message +" at linenumber: "+evt.lineno+" of file: "+evt.filename);
} else {
alert("error: "+evt.type+" from element: "+(evt.srcElement || evt.target));
}
}
jQuery.sap.log.addLogListener({
onLogEntry : function(oLogEntry) {
if(oLogEntry.level == '1'){
alert(oLogEntry.details + ' - '+oLogEntry.message);
}
}});
</script>
But I like to actually copy the error-message from the log into an alert for the customer, so he can send me screenshots of the error in his device.
All my attempts did not show enough information or didn´t fire on every error in the console-log.

Geolocation tracking not being asked for permission in chrome on desktop

I'm running basic code that just outputs the longitude and latitude on the screen or prints an error if something goes wrong.
function getMyLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation, displayError);
}
else {
alert("Oops, no geolaction support");
}
}
function displayLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var h1 = document.getElementById("location");
console.log("hey " + latitude + " " + longitude);
h1.innerHTML += " " + latitude + ", " + longitude;
}
function displayError(error) {
var errorTypes = {
0: "unkown error",
1: "Permission denied by user",
2: "Position is not available",
3: "Request timed out"
};
var errorMessage = errorTypes[error.code];
if(error.code == 0 || error.code == 2) {
errorMessage += " " + error.message;
}
var div = document.getElementById("location");
div.innerHTML = errorMessage;
}
When i run in firefox and internet explorer i get pop-ups asking for permission and the code runs fine. When I use my phone's google chrome browser i get asked for permission and everything works fine. When i try chrome on my desktop I never get asked permission and my error code runs and prints: "Permission denied by user". I've checked in my chrome settings and made sure my hostname is allowed and tried allowing any site to track my physical location but to no avail. What do?

Mixed Content Error (Http/Https)

I have mixed content error, on web site used both http and https protocols.
Here's the error from Chrome console:
Mixed Content: The page at 'https://www.amazon.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://www.amazon.com/../?redirect=true'. This request has been blocked; the content must be served over HTTPS.
Here's screenshot with the error: http://prntscr.com/9os5li
Was found some solution like:
Change link from "http://" to "https://" in
Blocked loading mixed active content.
Nothing helped me, because Amazon server drop it all the time when I change link in code or manual from http to https drop it and make it as http.
For example this one Link 2 I can't use here https, because of this I have mixed content error.
Here's my AJAX where I make a call:
$.ajax({
url: "//" + MWS_URL + rest_path,
data: request,
dataType: 'text',
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
beforeSend: function(req) {
//req.setRequestHeader("User-Agent", "chrome extension");
req.setRequestHeader("x-amazon-user-agent", "chrome extension");
},
success: function(data){
if (onSuccess) {
onSuccess(data);
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (onError) {
onError(jqXHR, textStatus);
}
}
});
setTimeout(callService, 1000);
}
Request:
requests.push(
$.get(link.URL, function (data) {
if (IsCancel()) {
return;
}
var jdata = $($.parseHTML(data));
var parser = new ProductPageParser(jdata, link.URL);
if (!parser.isValidProduct()) {
console.log(link.URL + " is not a valid product, skipped.");
link.processed = true;
return;
}
// Process associated (linked) product on this page according to user preferences.
crawlLinkedProducts(jdata, link.URL, config);
// Store product into a collection.
var product = getProductForParser(parser, link);
//product.dbRawProductURL = urlRaw;
if (product) {
products.push(product);
}
link.processed = true;
})
);
And as I have parse in parser, here's second level parser. I parsed products on main page:
$(productUrls).each(function (index, link) {
if (!link.processed) {
console.log("Download second level -> " + link.URL);
requests_2level.push(
$.post(link.URL, "", function (data) {
if (IsCancel()) {
return;
}
console.log("End download second level -> " + link.URL);
var jdata = $($.parseHTML(data));
var parser = new ProductPageParser(jdata, link.URL);
if (!parser.isValidProduct()) {
console.log(link.URL + " is not a valid product, skipped.");
link.processed = true;
return;
}
var hackUrl = "//amazon.com/o/ASIN/" + parser.getAsin();
link.URL = hackUrl;
var product = getProductForParser(parser, link);
if (product) {
products.push(product);
}
link.processed = true;
})
);
}
});
Anyone have idea how to fix this problem?
If Amazon keep redirecting you from HTTPS to HTTP then there is nothing you can do about that short of:
Complaining hard enough at Amazon that they fix it or
Using a difference service
Decide whether to use http or https and use the same on for every call.

Check for an specific .js file being served in response

I need to detect whether an specific .js file was served in a http response and additionally, check the domain it came from, like this:
I need to automatically detect the lack of the js file and email the incidence
I tried Net::Http, rest-client, mechanize and a lot of gems, they just return the html header. It seems I need to monitor http traffic with tools like PhantomJS and checking for the file, but is there any rubyesque way of doing this?
Thanks in advance
I ended with the phantomjs approach. A ruby script iterate over a database table and then calls this phantomjs script for each record representing an URL
This is the phantomjs script
var page = require('webpage').create(),
system = require('system'),
address,
isScript = false;
var fs = require('fs');
// main
analizePage(system.args[1]);
//open page.
//onResourceRequested event, compares domain of each one with 'my.domain.net'
//append to a log file: -1 for failed url, 1 for script presence, 0 for no script presence
function analizePage(address){
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address ' + address);
fileWriter(-1, address);
}
else
{
if (!isScript){
fileWriter(0, address);
}
else
{
fileWriter(1, address);
}
console.log('Has script: ' + isScript);
}
phantom.exit(0);
});
page.onResourceRequested = function (req) {
try {
var link = document.createElement('a');
link.setAttribute('href', req.url); //extract asset's domain from URL
if (link.hostname == 'my.domain.net') {
isScript = true;
}
} catch(e) {
console.log("PAGE OPEN ERROR: " + e);
}
};
}
function fileWriter(type, line){
try {
fs.write("scriptlog.csv", type + ',' + line + ',' + Date.now() + ',' + system.args[2] + '\n', 'a');
} catch(e) {
console.log("FILE ERROR: " + e);
}
}

Categories