working on side project using openweathermap api...
i am using my own api key, the one mentioned here is generic and works for someone who doesnt have an account, it's free anyways...
Also i am using bootstrap toggle lib...
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Weather Now</Title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<h1 class="text-center">Local Weather</h1>
<input id="tog" type="checkbox" checked data-toggle="toggle" data-size="large" data-on="℃" data-off="℉" data-onstyle="primary" data-offstyle="success">
<ul>
<li id="city"></li>
<li id="weatherType"></li>
<li id="temp"></li>
<li id="windSpeed"></li>
</ul>
</body>
</html>
JS/jQuery:
$(document).ready(function(){
var long,lat,weatherType,temp,kelvin,celsius,fahrenheit,city,apiObj;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
long = position.coords.longitude;console.log(long);
lat = position.coords.latitude;console.log(lat);
apiObj = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&appid=b1b15e88fa797225412429c1c50c122a1";
console.log(apiObj);
$.getJSON(apiObj,function(data){
console.log("hi");
weatherType = data.weather[0].description;console.log(weatherType);
kelvin = data.main.temp;console.log(kelvin);
fahrenheit = (kelvin)*(9/5)-459.67;console.log(fahrenheit);
celsius = kelvin-273;console.log(celsius);
city = data.city;console.log(city);
if($('#tog').prop('checked')){
$('#temp').html('hi '+celsius); //doesnt work
}
else{
$('#temp').html(fahrenheit);
}
});
console.log("bye");
});
}
});
Example JSON:
http://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b1b15e88fa797225412429c1c50c122a1
{
"coord":{
"lon":139.01,
"lat":35.02
},
"weather":[
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01n"
}
],
"base":"stations",
"main":{
"temp":285.514,
"pressure":1013.75,
"humidity":100,
"temp_min":285.514,
"temp_max":285.514,
"sea_level":1023.22,
"grnd_level":1013.75
},
"wind":{
"speed":5.52,
"deg":311
},
"clouds":{
"all":0
},
"dt":1485792967,
"sys":{
"message":0.0025,
"country":"JP",
"sunrise":1485726240,
"sunset":1485763863
},
"id":1907296,
"name":"Tawarano",
"cod":200
}
Console Output:
Outputs Long, Lat, api-url and bye...nothing in between(the code in getJSON)...
What's happening?
UPDATE:
So as mentioned by the ppl here i checked stuff and it was throwing an error...the error was "Blocked loading mixed active content”
What is Mixed Content?(refered from stackoverflow answer)
When a user visits a page served over HTTP, their connection is open for eavesdropping and man-in-the-middle (MITM) attacks. When a user visits a page served over HTTPS, their connection with the web server is authenticated and encrypted with SSL and hence safeguarded from eavesdroppers and MITM attacks.
However, if an HTTPS page includes HTTP content, the HTTP portion can be read or modified by attackers, even though the main page is served over HTTPS. When an HTTPS page has HTTP content, we call that content “mixed”. The webpage that the user is visiting is only partially encrypted, since some of the content is retrieved unencrypted over HTTP. The Mixed Content Blocker blocks certain HTTP requests on HTTPS pages.
The API call provided by 'openweathermap' is 'http', in my case since it is a side project i hard coded/added 's' making it 'https' and it worked!
If you are writing professional code i suggest ask API vendor for https/secure connection! Thanks for all the help!
The thing between "api-url" and "bye" is the jQuery.getJSON() call. That function in there is the success-callback. That fact that it does not get executed, means that the getJSON() must not have completed successfully.
To figure out why, you should debug that request.
Does that URL give a response at all?
Is it a success-response (status code 2xx)?
Does it return JSON?
If none of those help you, you could convert the getJSON-call to a $.ajax-call and add an error-callback. That should certainly get called. See what kind of error it gets.
$.ajax({
dataType: "json",
url: apiObj,
success: function (data) { /* your function body */ }
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR, textStatus, errorThrown);
console.error(jqXHR.responseJSON);
});
Update: I am getting 401 Unauthorized as a response.
{
"cod": 401,
"message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."
}
Related
I'm having trouble reliably triggering a Firebase Cloud Function via the HTTP trigger method. It doesn't work in all browsers, and sometimes only works if you reload the page. The html webpage is hosted with Firebase Hosting.
Premise is simple, main html page has a button which when pressed, sends the HTTP request to the Cloud Function, and then navigates to another page saying done. The Cloud Function sends an FCM notification and works reliably when manually using the HTTP request url.
Is there something wrong with my HTTP request in scripts.js? What would make this very inconsistent behaviour? It works generally in Chrome, not in Firefox, and sometimes in Edge.
index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel=icon href=favicon.ico>
<title>Title</title>
</head>
<body>
<h1>New heading</h1>
<input type="button" value="Send FCM" onclick="doThing()">
<script src="scripts.js"></script>
</body>
</html>
scripts.js looks like this
var request = require('request')
function doThing(){
const url = '<HTTP request URL>';
request(url, function(error, response, body){
if (!error && response.statusCode == 200){
window.location.href = "outro.html";
}
})
}
and outro.html looks like this;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<body>
<h1>Cya</h1>
</body>
</body>
</html>
For clarity, this is the Cloud Function script:
const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.https.onRequest((request, response) =>{
var topic = 'all';
var payload = {
notification:{
title: 'Title!',
body: 'Test!'
},
};
return admin.messaging().sendToTopic(topic, payload).then((res) =>{
response.status(200).send("ok");
return console.log("Success:");
}).catch((err) =>{
console.log("Error: ", err);
response.status(500).send("bad");
});
});
All are deployed with firebase deploy.
We are using jQuery 3.3.1 in our project. When we are using and testing on localhost the jQuery works fine and its loading without any issue.
However, now we have deployed our web application on AWS and after deploying it is giving the below error
Failed to load resource : the server responded with a status of 500 (Internal Server Error)
We are loading third party payment providers iFrame in our html page. Is that causing an issue ? If it is an issue then why does it works fine in localhost ?
Also, we have kept the file in our solution itself and tried with jQuery CDN as well. But it gives the same error.
#using Microsoft.AspNetCore.Mvc.Rendering;
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>PaymentProviders</title>
<script src="~/jquery.min.js"></script>
</head>
<body>
<div class="form-control">
<label>Payment Provider Name:- </label>
#Html.DropDownList("ID", new SelectList(ViewBag.PaymentProvidersList, "ID", "PaymentProviderName"), "Please select", new { #id = "ddlPaymentProviders", #onChange = "SelectedValue(this)" })
</div>
<div id="divContainer"></div>
</body>
</html>
<script>
function SelectedValue(ddlObject) {
var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;
$.ajax({
type: "GET",
url: "/Home/Index",
data: { 'paymentProviderName': selectedText },
success: function (data) {
$('#divContainer').html(data);
$('#divContainer iframe').height("500");
}
});
}
</script>
Below is the screenshot for the same.
Any help on this appreciated !
I am using the following two files attached.
index2.html file located on the local server which is calling the JavaScript file which is also located on the local machine
fetch-ajax3.js - JavaScript file located on the local server consisting of the function and method to authenticate and authorize the API call and retreive data and post it in the console.
I am not sure what to input in redirect URI.
Can someone help?
Resolution - i was able to resolve the issue after whitelisting the callback uri in the spotify api app.
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
if (item) {
var parts = item.split('=');
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = '';
// Set token
let _token = hash.access_token;
const authEndpoint = 'https://accounts.spotify.com/authorize';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = '';
const redirectUri = '';
const scopes = [
'user-top-read'
];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token&show_dialog=true`;
}
// Make a call using the token
$.ajax({
url: "https://api.spotify.com/v1/me/top/artists",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
success: function(data) {
// Do something with the returned data
data.items.map(function(artist) {
let item = $('<li>' + artist.name + '</li>');
item.appendTo($('#top-artists'));
});
}
});
<html>
<head>
<title>Spotify Implicit Grant Template</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="./fetch-ajax3.js" defer></script>
</head>
<body class="container">
<h1 class="text-salmon">Spotify Implicit Grant Template</h1>
<h3>This app uses the implicit grant authorization flow to authenticate users and get user data.</h3>
<p>
Here are your top artists on Spotify:
<ol id="top-artists"></ol>
</body>
</html>
After whitelisting the callback url in the app , i was able to connect it.
specify your URL as Http for localhost in the app settings in your Spotify dashboard
You need to add your URL in Redirect URI which will whitelist your URL. It works for me.
I am trying to make the codes you see here:
https://glitch.com/edit/#!/amusing-swallow?path=index.html:7:68
executable on my node js application. Please note that the codes on that link is working.
What I did is that I set up an environment like this:
root folder
--public
--index.html
--script.js
--app.js
--package.json
And then I copied the html code to my index.html file like this:
<!DOCTYPE html>
<html>
<head>
<title>Spotify Implicit Grant Template</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body class="container">
<h1 class="text-salmon">Spotify Implicit Grant Template</h1>
<h3>This app uses the implicit grant authorization flow to authenticate users and get user data.</h3>
<p>
Here are your top artists on Spotify:
<ol id="top-artists"></ol>
</p>
<script src="../script.js" type='text/javascript'></script>
</body>
</html>
Nothing special and then I made the script.js a self invoking function like this:
(function() {
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split("&")
.reduce(function(initial, item) {
if (item) {
var parts = item.split("=");
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = "";
// Set token
let _token = hash.access_token;
const authEndpoint = "https://accounts.spotify.com/authorize";
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = "xxxxxxxxxxxxxxxxxxxxxxxx";
const redirectUri = "http://localhost:8888/callback/";
const scopes = ["user-top-read"];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join(
"%20"
)}&response_type=token&show_dialog=true`;
}
// Make a call using the token
$.ajax({
url:
"https://api.spotify.com/v1/search?query=tania+bowra&offset=0&limit=20&type=artist",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + _token);
},
success: function(data) {
// Do something with the returned data
data.items.map(function(artist) {
let item = $("<li>" + artist.name + "</li>");
item.appendTo($("#top-artists"));
});
}
});
})();
And then finally on my app.js for express:
var express = require("express"); // Express web server framework
var app = express();
app.use(express.static(__dirname + "/public"));
console.log("Listening on host 8888......");
app.listen(8888);
So I tried to run this and whenever I visit the localhost:8888, I keep on getting these:
GET http://localhost:8888/script.js 404 (Not Found)
Refused to execute script from 'http://localhost:8888/script.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
I am not sure why. But I just copied the same exact code and just put my credentials there but it won't still work. Any idea what am I doing wrong?
I'm trying to scrape a web page, but getting some weird results in my browser's console (as seen below). Here's my code:
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Icefilms Searcher</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<script type="text/javascript" src="script.js"></script>
<div id="container" style="width:1100px;position:relative;"></div>
</body>
</html>
script.js
$(document).ready(function(){
var currNum = 168000;
var maxNum = 168005;
function generateNextUrl(){
currNum++;
return currNum-1;
}
scrapeThis(generateNextUrl());
function scrapeThis(theUrl){
$.ajax({
url:
"php.php",
data:
"icefilmsURL=" + theUrl,
success:
function(response){
var movieTitle = $(response).find("#videotitle").find("span:first").text();
$("#container").append("<a href='http://www.icefilms.info/ip.php?v="+theUrl+"' target='blank'>"+movieTitle+"</a><br>");
},
complete:
function(){
if(currNum < maxNum+1){
scrapeThis(generateNextUrl());
}
},
error:
function(xhr,err){
$("#container").append("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
$("#container").append("responseText: "+xhr.responseText);
}
});
};
});
php.php
<?php
echo file_get_contents("http://www.icefilms.info/ip.php?v=".$_GET["icefilmsURL"]);
?>
The code works fine, but this is what I see in my console:
Any ideas?
You are seeing those in the console because the page you are scraping contains references to relative paths.
That is to say rather than
<img src="http://www.icefilms.info/someimage.jpg">
The code is
<img src="someimage.jpg">
Therefore, when you grab and display their HTML on your own domain the browser is trying to load the image from your domain, localhost in this case. But you do not have the image on your server.
You can use a base href in the HTML to resolve this, or you could find and replace relative path images to include the domain.
<base href="http://www.icefilms.info/">