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.
Related
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
})
The javascript inside my page needs to download the small text file (just a small JSON Array) that resides in the following location:
http://dadosabertos.rio.rj.gov.br/apiTransporte/apresentacao/rest/index.cfm/obterPosicoesDaLinha/410
The MIME type of the document is application/json.
I tried with a XMLHttpRequest but I got an error:
XMLHttpRequest cannot load http://dados[...]/410. No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'null' is therefore not allowed access.
I googled this, and the solutions pointed to CORS and to change things on the server side, something I cannot do.
Is there any way to retrieve this content with javascript (and only javascript)?
Thanks!
L.
EDIT
Following #naresh advice, I am trying with JSONP. I added these lines to my page, but nothing happens (not even a console error):
var source = "http://dados[...]/409";
script = document.createElement('script');
script.type = 'text/javascript';
script.src = source + '?callback=downloadLinha';
document.body.appendChild(script);
My function downloadLinha(data) is just alert(data).
EDIT 2
I contacted the server administrator, and, to my surprise, they fixed the problem in a couple of hours! I didn't expect they would even answer. So my actual problem is solved, but I could not find an answer without the administrator intervention.
Anyway, thanks A LOT to all that tried to help!
Similar to what #RobertHarvey said, the lack of a header doesn't let you access it... Via Chrome, that is. You might still be able to access it using this handy tool called anyorigin.
Check it out: http://anyorigin.com/
Nope, no can do! If I could, I would hava javascript silently load the contents of www.yourbank.com via AJAX and read whatever it can. Don't you think this is a dangerous feature with the prevalence of auto-login on the web?
You can use a proxy server, which will work as long as the target file does not depend on user-specific cookies, headers, etc.
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.
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.
What would I need to do to get this example running on my machine?
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_httprequest_js (page no longer available)
I'm looking to access the XML file hosted on w3schools (and not move it to my machine), but run the HTML and Javascript code on my machine. I tried changing the third to last line from:
<button onclick="loadXMLDoc('note.xml')">Get XML</button>
to:
<button onclick="loadXMLDoc('http://www.w3schools.com/ajax/note.xml')">Get XML</button>
thinking this would make it work, but it didn't seem to help. Any suggestions?
Just put the full URL into your browser window which will let your browser get it, then copy/paste and save locally. Javascript won't fetch stuff from outside the domain it's served from (without a fair bit of extra work), due to the Same Origin policy ( a security feature).
You can't go cross domain using AJAX. You should move the XML file to the same server that you have the site files stored on and call it that way.
https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript
You need to use the following code in the function that does the AJAX:
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesRead");
} catch (e) {
alert("error");
}
This only works for Firefox! There are other options which can be passed to enablePrivilege that may be useful.