Openweathermap API on Githubpages - javascript

I have a project I finished , and when you upload it on Github pages it doesn't work. It won't bring in any scripts, externally linked fonts, and API data. The API only supports HTTP, and Github pages only accepts HTTPS. Any way around it without changing API's?
The API is Openweathermap.
$(document).ready(function(){
var temp = $('.temperature');
var APIKEY = ';
var loc = $('#search').val();
function updateByCity(loc){
var url = "http://api.openweathermap.org/data/2.5/weather?q=" + loc + "&APPID=" + APIKEY;
sendRequest(url);
}
function k2f(k){
return Math.round(k*(9/5)-459.67);
}
function ascii(a){
return String.fromCharCode(a);
}
$('.enter').click(function(event){
event.preventDefault();
var loc = $('#search').val();
var url = "http://api.openweathermap.org/data/2.5/weather?q=" + loc + "&APPID=" + APIKEY;
console.log(url);
var xmlhttp = new XMLHttpRequest ();
xmlhttp.onreadystatechange = function(){
var url = "http://api.openweathermap.org/data/2.5/weather?q=" + loc + "&APPID=" + APIKEY;
console.log("lol");
var data = JSON.parse(xmlhttp.responseText);
var datatext = data.id;
var name = data.name;
var locname = name;
var temptext = k2f(data.main.temp) + ascii(176) + "F";
console.log(temp);
console.log(url);
$('.temperature').text(temptext);
$('.city').text(name);
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
});

No, there won't be an easy way around this restriction as it is important for the security and integrity of your website. If you access resources from an HTTPS encrypted page via an unencrypted connection, the user will always see security warnings.
You could set up a proxy that accesses the API via HTTP and passes the calls on to the browser via HTTPS. Note that this may cause considerable overhead in terms of development effort.
The simplest solution would probably be to switch to a different weather data provider, considering that HTTPS encryption by default may be a good idea.

Related

How to get "file" parameter of http request in javascript?

I'm trying to program a java script script that based on whether a user logs in properly or not will redirect them to a separate PHP script. The issue is that I can't seem to figure out how to get the file parameter of the request so that I can see if the request I'm looking for is there. How do I get the file parameter of a request in java script?
Sorry for misconceptions, what i mean by the file attribute is what is under the "file" section for each request in the following.
example
So if under the file tab of the packet, it set a certain file, how would i differentiate?
It's not clear what you're asking.
The part " so that I can see if the request I'm looking for is there" tells me, you want to debug your website, or at least, that's my interpretation of it.
If you use Chrome or Firefox Developer Edition, you can press F12 (or CTRL + SHIFT + J) to open the developer console.
Change to the tab "Network, and you'll see all the XMLHTTPRequests.
Click on a specific request, and you'll see its details.
A basic XmlHttpReuqest goes like this:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
And you get the result of your request in the callback function reqListener.
See also https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
If you want to get the request handler's URL, that goes like this:
function reqListener (e) {
//console.log(this.responseText);
console.log(e);
console.log(e.currentTarget.responseURL);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://stackoverflow.com/questions/58407228");
oReq.send();
And if you want to get a parameter called "file" inside an url, this goes like
function getUrlVars(urlHref)
{
var vars = [], hash;
var hashes = urlHref.slice(urlHref.indexOf('?') + 1).split('&');
var i;
for (i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
} // Next i
return vars;
} // End Function getUrlVars
var dictParameters = getUrlVars("http://www.example.com/handler?file=bla.bin");
if (dictParameters.contains("file"))
{
console.log(dictParameters["file"]);
}
As for XMLHTTPRequest, it doesn't have a property called file.
Also, this is 2019, you should be using the FETCH-API with async and await, not the XMLHttpRequest-API, which doesn't use promises.
Here's a getting started overview.
Edit:
Ah, I see:
If you have a url, such as
var url = "http://www6.scratch99.com/web-development/javascript/test.js?abc=def";
you do
var url = "http://www6.scratch99.com";
var urlParts = url.replace('http://','').replace('https://','').split(/[/?#]/);
var domain = urlParts[0];
to get the domain part. Then you subtract the domain (+protocol), and end it at ? or #:
Full code:
var url = "http://www6.scratch99.com/web-development/javascript/test.js?abc=def";
// var url = "http://www6.scratch99.com";
// var url = "http://www6.scratch99.com?test=123";
var protocol = url.substr(0, url.indexOf(":") + 3)
var urlParts = url.substr(protocol.length).split(/[/?#]/);
var domain = urlParts[0];
var fileParts = url.substr(protocol.length + domain.length);
var file = fileParts.split(/[?#]/)[0];
and if you want the filename only:
var pathParts = file.split('/');
var fileOnly = pathParts[pathParts.length-1];

Google App Script: Authentication failing on UrlFetchApp.Fetch()

My code:
var username = "";
var password = "";
var options = {};
options.headers = {
"Authorization": "Basic " + Utilities.base64Encode(username + ":" + password)
};
var html = UrlFetchApp.fetch("https://www.4for4.com/fantasy-football/full-impact/cheatsheet/Flex/38351/ff_nflstats/adp_blend", options).getContentText();
Logger.log(html);
I read through a few posts like this one but still having trouble getting the data I need. The result is HTML from the redirected login page. Is it possible this site uses a different Authorization type or do I need to pass something else in the header?

Dynamics Crm Invoking Workflow from external source

Scenario:
I would like to invoke an already defined workflow or a custom action from a web page which is located outside the CRM Dynamics context. (Let's say MS CRM 2011-2013-2015-2016 and 365)
My solution:
My idea would be about defining a kind of controller page into the CRM context accessible from the web and execute the rest call within that page (through javascript).
This page will be able to read input parameters and execute the right rest call.
Does it make sense? Could you suggest a better implementation?
Thanks in advance!
If you have the resources, you can setup a service utilizing the following methods and then ajax it.
private static void ExecuteWorkflow(Guid workflowId, Guid entityId)
{
try
{
string url = ConfigurationManager.ConnectionStrings["crm"].ConnectionString;
ClientCredentials cc = new ClientCredentials();
cc.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
OrganizationServiceProxy _service = new OrganizationServiceProxy(new Uri(url), null, cc, null);
ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
{
WorkflowId = workflowId,
EntityId = entityId
};
ExecuteWorkflowResponse r = (ExecuteWorkflowResponse)_service.Execute(request);
_service.Dispose();
}
catch (Exception ex)
{
//Handle Exception
}
}
If you're unable to have the service on the same domain as the CRM server, you should be able to impersonate.
cc.Windows.ClientCredential.Domain = "DOMAIN";
cc.Windows.ClientCredential.Password = "PASSWORD";
cc.Windows.ClientCredential.UserName = "USERNAME";
You can find more details here.
https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.executeworkflowrequest.aspx
You can invoke a workflow in a js like this:
You can query the workflowId by its name and the type definition.
var entityId = // The GUID of the entity
var workflowId = // The GUID of the workflow
var url = // Your organization root
var orgServicePath = "/XRMServices/2011/Organization.svc/web";
url = url + orgServicePath;
var request;
request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<s:Body>" +
"<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">" +
"<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>EntityId</c:key>" +
"<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + entityId + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>WorkflowId</c:key>" +
"<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + workflowId + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"</a:Parameters>" +
"<a:RequestId i:nil=\"true\" />" +
"<a:RequestName>ExecuteWorkflow</a:RequestName>" +
"</request>" +
"</Execute>" +
"</s:Body>" +
"</s:Envelope>";
var req = new XMLHttpRequest();
req.open("POST", url, false);
// Responses will return XML. It isn't possible to return JSON.
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.send(request);
If the request.status is 200 the request was succesfull. This was tested on an CRM2011 enviroment.
I recommend you to create a WCF rest or web api, reference the IOrganizationService and from that use the operation of the CRM service. It is better to call a intermediate WCF than the IOrganizationService directly.

AWS S3 with SAML

I am trying to upload files to S3 from an app written in JavaScript. For this reason - mobile app, I am limited to libraries that I could use. Got the thing to work by using FormData until it was decided to use SAML and delegate authentication. Now, the temporary credentials are being obtained OK. However, AWS::S3 does not want to recognize them. It throws an error: The AWS Access Key Id you provided does not exist in our records.
My code is below:
console.log("AWS temp credentials: " + JSON.stringify(delegated_jwt.Credentials));
var aws_creds = delegated_jwt.Credentials;
var secret = aws_creds.SecretAccessKey;
var policyBase64 = base64.encode(JSON.stringify(POLICY_JSON));
console.log ("policy base64: " + policyBase64 );
var signature = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(policyBase64, secret));
console.log("signature: " + signature);
var key = "user_uploads" + "/" + delegated_jwt.Subject + '/' + (new Date).getTime() + ".jpg";
console.log("AWS::S3 key: " + key);
var params = new FormData();
params.append('key', key);
params.append('acl', 'private');
params.append('Content-Type', "image/jpeg");
params.append('AWSAccessKeyId', aws_creds.AccessKeyId);
params.append('policy', policyBase64);
params.append('signature', signature);
params.append('file', captured.uri);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://mybucket.s3.amazonaws.com/', true);
xhr.onload = () => {
...
When I used permanent access and secret keys, it worked fine. If this there is something wrong with my AWS settings, how do I debug this? What else should I check?

Using CORS to list files on Google Drive

This is probably a dumb question, but I am new to Web programming. I am trying to communicate with the Google Drive using client side JavaScript and CORS. I first used the jsclient library and that worked fine:
request = gapi.client.drive.files.list( {'q': " trashed = false " } );
Using CORS, my code looks like:
var xhr = new XMLHttpRequest();
xhr.open('GET','https://www.googleapis.com/drive/v2/files');
var mysearch = encodeURIComponent("q=trashed=false");
xhr.open('GET',"https://www.googleapis.com/drive/v2/files?" +mysearch,true);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() { handleResponse(xhr.responseText); };
xhr.onerror = function() { handleResponse(null); };
xhr.send();
I have tried:
var mysearch = encodeURIComponent("q=trashed=false");
var mysearch = encodeURIComponent("trashed=false");
var mysearch = encodeURIComponent("q='trashed=false'");
They all return the list of all the files. If I don't have a search string, I also get all the files.
I would like to have other search parameters also, using &, but I can't get just one to work.
How do I format the mysearch string?
Encode only the value part of the parameter:
var url = 'https://www.googleapis.com/drive/v2/files?q=' + encodeURIComponent("'trashed=false'")

Categories

Resources