Ajax / Firebase only works on localhost (same-origin policy?) - javascript

I have a Firebase app that works perfectly on localhost, but does not work when I reach it externally (by allowing port forwarding in my router) or when I upload it to Bluehost.
This code works:
$(document).ready(function() {
$("#button").click(function() {
alert('Working!');
});
});
but this does not:
var firebaseRef = new Firebase('[my firebase url]');
$(document).ready(function() {
$("#button").click(function() {
alert('Working!');
});
});
After doing some research, I believe the problem to be the Same Origin Policy, since the Firebase JS include is
http://static.firebase.com/demo/firebase.js
but my firebase reference is on
http://gamma.firebase.com/
I've found a few ways to get around this but want to know the best way to handle it with Firebase (or if the Same Origin Policy is even the issue here).

I found the answer - just a dumb mistake on my part.
While searching through the Firebase tutorials, I caught my mistake. I was including the http://static.firebase.com/demo/firebase.js file, while the tutorial clearly says to include the http://static.firebase.com/v0/firebase.js file.
I am still curious as to why the demo file worked only on localhost...

Firebase uses CORS for the RESTful API and WebSockets for the JS clients, see this answer, so that's not an issue.
Looks like a problem related to the routing. Are you experiencing errors in the JavaScript console? "Does not work" is a bit abstract and a more precise error could help answer the secondary question.

Related

CORS 400 header missing (among other issues)

This is my first project using javascript (basically forked code from here: https://www.kkhaydarov.com/audio-visualizer/)
I'm trying to build a visualizer that responds to the audio I am hosting.
Problems:
- Getting thrown a CORS 400 error (i'm using https://cors-anywhere.herokuapp.com/http:// in my source url)
- Audio is not getting recognized
Here is a link to my project on codepen: https://codepen.io/beewash92/project/editor/ZGWOQr
Code is also stored on my github: https://github.com/beewash/js-audio-visualizer
enter code here
I've scoured other posts on stackoverflow and across the web, but still running into issues. You're help is appreciated !
If you try to browse the link in chrome you will get the message as below
Missing required request header. Must specify one of: origin,x-requested-with
You will need to define the custom request header as stated above in order for it to work. Refer the api here as it clearly stated what you should do beforehand.
You should create a request with the header as follows
fetch('https://cors-anywhere.herokuapp.com/http://soundcloud.com/gentttry/10999-1', {
'headers': {
'Origin': 'soundcloud.com'
}
})
.then(res=>res.blob())
.then(blob=>URL.createObjectURL(blob))
.then(audio_src=>{
// Then init your audio here and assign the url
})

stomp+ActiveMQ with SSL

I have used stomp+ActiveMQ in my application to push the data events received from external applications. I am able to setup this on HTTP [ws] but when I tried moving this setup to my production server where we have HTTPS [wss], the setup is failing with error saying un-authorised access. I understand it is because of the SSL what we have on production server, but I am unable to find out solution for this, I tried searching and tried following the proposed solutions but none are working. Any help would be highly appreciated.
Update 1: Adding the details asked
Here is the code what I have added for STOMP
var client = Stomp.client("wss://domain:61614/stomp");
And the error I get is "ReferenceError: Stomp is not defined"
activemq : 5.9.0
STOM : 1.0.9
it's a js side log, did you have included your js stomp file ??
<script src='stomp.js'></script>
https://github.com/apache/activemq/tree/master/activemq-web-demo/src/main/webapp/websocket
I resolved the issue, and it was related to the key strokes what I had generated earlier. I just deleted the previous one and recreated a new one for my SSL and everything started working with the sample application provided by STOMP team. I will integrate it in my actual project and will paste the solution here for everyone use.
Following are the settings we had used.
transportConnector name="wss" uri="wss://0.0.0.0:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600&wireFormat.maxInactivityDuration=500000000&wireFormat.maxInactivityDurationInitalDelay=36000000&websocket.maxIdleTime=0&transport.useInactivityMonitor=false"

Reading code from GitHub as text (raw) in a web page

I'm trying to read some source code (C language) from my GitHub repository to be shown as text in my webpage. I can access the code in raw mode through https://raw.github.com.
I'm using jQuery GET function to read the data but it doesn't work. Problem is related with XMLHttpRequest and Access-Control-Allow-Origin but, despite I found some related question on stackoverflow (XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin) it didn't work for me. I tried everything.
My jQuery code:
<script type="text/javascript">
$(document).ready(function() {
var url = 'https://raw.github.com/raysan5/raylib/master/examples/ex01_basic_window.c';
$.get(url, function(data) {
$('#code').text(data);
}, 'text');
});
</script>
Please, could someone help me with this issue? Many thanks!
You could try and delete the dot between raw and github:
https://rawgithub.com/raysan5/raylib/master/examples/ex01_basic_window.c
See rawgithub.com, also explained in this blog post:
GitHub discourages this, since they want repo owners to use Github Pages to host specific versions of their files. They discourage it by serving files from the “raw” domain with Content-Type: text/plain instead of Content-type:application/javascript.
This wasn’t a problem until recently, when Google Chrome implemented a security fix that prevents JavaScript from being executed if it has an incorrect Content-type.
This makes sense when you’re viewing pages outside of your control. But when it’s you who’s deciding what scripts to include, it’s a hassle.
As Rob W comments below:
It's worth mentioning that the only reason that this web service solves the OP's problem is that it includes the Access-Control-Allow-Origin: * response header.

gapi.client.load not working

I have the following code, which is supposed to be a simple example of using the google api javascript client, and simply displays the long-form URL for a hard-coded shortened URL:
<script>
function appendResults(text) {
var results = document.getElementById('results');
results.appendChild(document.createElement('P'));
results.appendChild(document.createTextNode(text));
}
function makeRequest() {
console.log('Inside makeRequest');
var request = gapi.client.urlshortener.url.get({
'shortUrl': 'http://goo.gl/fbsS'
});
request.execute(function(response) {
appendResults(response.longUrl);
});
}
function load() {
gapi.client.setApiKey('API_KEY');
console.log('After attempting to set API key');
gapi.client.load('urlshortener', 'v1', makeRequest);
console.log('After attempting to load urlshortener');
}
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
except with an actual API key instead of the text 'API_KEY'.
The console output is simply:
After attempting to set API key
After attempting to load urlshortener
but I never see 'Inside makeRequest', which is inside the makeRequest function, which is the callback function for the call to gapi.client.load, leading me to believe that the function is not working (or failing to complete).
Can anyone shed some light on why this might be so and how to fix it?
Thanks in advance.
After spending hours googling the problem, I found out the problem was because I was running this file on the local machine and not on a server.
When you run the above code on chrome you get this error in the developer console "Unable to post message to file://. Recipient has origin null."
For some reason the javascript loads only when running on a actual server or something like XAMPP or WAMP.
If there is any expert who can shed some light to why this happens, it would be really great full to learn.
Hope this helps the others noobies like me out there :D
Short answer (http://code.google.com/p/google-api-javascript-client/issues/detail?id=46):
The JS Client does not currently support making requests from a file:// origin.
Long answer (http://en.wikipedia.org/wiki/Same_origin_policy):
The behavior of same-origin checks and related mechanisms is not well-defined
in a number of corner cases, such as for protocols that do not have a clearly
defined host name or port associated with their URLs (file:, data:, etc.).
This historically caused a fair number of security problems, such as the
generally undesirable ability of any locally stored HTML file to access all
other files on the disk, or communicate with any site on the Internet.

Origin null is not allowed by Access-Control-Allow-Origin

I'm currently working with the SoundCloud API and would like to have a track embed when a button is clicked.
I get two errors:
XMLHttpRequest cannot load http://soundcloud.com/oembed.json?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F48419073. Origin null is not allowed by Access-Control-Allow-Origin.
AND
Uncaught TypeError: Cannot read property 'html' of null
Here is my code:
<button onclick="getPopular()">+1</button>
<div id="track"></div>
<script src="http://connect.soundcloud.com/sdk.js" type="text/JavaScript"></script>
<script type="text/JavaScript">
SC.initialize({
client_id: "**************",
});
var getPopular = function() {
SC.get("/tracks", {limit: 1}, function(tracks) {
var track = tracks[0];
alert("Latest track: " + track.title);
SC.oEmbed(track.uri, document.getElementById("track"));
});
};
</script>
I use an alert in my code to let me know that it is actually taking information from the SoundCloud API. I'm just not sure what else is preventing it from embedding.
Thanks, ahead of time, or looking at my question.
jiggabits
Read a little about Same Origin Policy to understand your main problem better. Ajax, localhost and Chrome/Opera don't go well together. This related question is even better.
Your second problem is due to the Ajax call (somewhere in your API) which doesn't return an html response due to the first error.
Instead of explaining the issue (which is very well explained in the links above), I'll provide a solution. Since you're running on Chrome, there's an workaround for that. Start chrome with this option:
--allow-file-access-from-files
(workaround which I shamelessly borrowed from Pointy)
You could also try running it on Firefox, or hosting it temporarily. :)
P.S. If you plan on doing serious development from your local machine, you may consider installing Apache to serve and test content through http://localhost, thus lifting the file:/// restrictions.
Here are some excellent tools that come with Apache and PHP pre-configured for development:
For Windows: EasyPHP, WAMP.
Cross-platform: XAMPP, BitNami.
If you're getting a track back, the I would try, alert(document.getElementById("track")); to make sure that you're getting your dom element.

Categories