Random Quote Generator CORS issue

Hi All,

I’m struggling with the random quote machine. I’ve gone through the documentation, added the JSONP to the URL, but I am getting the CORS error below and I have no idea how to solve it. I just want to get a quote showing, with the author, in my HTML.

Thanks for your help,

“Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&jsonp=mycallback&=1504281048393. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://null’).”

$(document).ready(function(){
	
	$("#get-quote").on("click", function(){
		
		var API_URL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback";
		
		//Pull quote from API
		$.ajax({
			url: API_URL,	
			success: function(data){
				data.shift();
				$("#quote-title").text(post.title);
				$("#quote-content").html(post.content);
					if (typeof post.custom_meta !== 'undefined' && typeof post.custom_meta.Source !== 'undefined') {
						$('#quote-source').html('Source:' + post.custom_meta.Source);
				} else {
				  $('#quote-source').text('');
				}
			},
			cache:false
		});
	});
});

Thanks for the help, but I’m still getting the same error coming back? New code below.


$(document).ready(function(){
	
	$("#get-quote").on("click", function(){
		
		var API_URL = "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
		
		//Pull quote from API
		$.ajax({
			url: API_URL,	
			success: function(){
				$("#quote-title").text(post.title);
				$("#quote-content").html(post.content);
					if (typeof post.custom_meta !== 'undefined' && typeof post.custom_meta.Source !== 'undefined') {
						$('#quote-source').html('Source:' + post.custom_meta.Source);
				} else {
				  $('#quote-source').text('');
				}
			},
			cache:false
		});
	});
});

Hi Kubix,

If you hit the page directly in your browser, do you get a response that includes the data you’re expecting? Because i am, just want to know if you aren’t for some reason.

/**/mycallback([{“ID”:421,“title”:“Rem Koolhaas”,“content”:“

The good is not a category that interests me. </p>\n”,“link”:“https://quotesondesign.com/rem-koolhaas/”}])

If the server has disallowed CORS (i.e. specified that requests must come from the same domain) then you can’t access that resource with jQuery. But there is a work-around using script tags, which circumvent the CORS restriction. It’s nuts, but it works.

Check out this page for more info:

Note: the callback has to be defined before the script tag runs.

My console is not showing this, all I’m getting is the same CORS error. I’ve tried the suggested changes and I’m still just getting that same CORS error in the console.

Hi

I’m getting that CORS message when I click on my button in firefox or chrome. I’m using notepad++ if that helps at all. I have no idea why mine is not working.

I’ve thrown myself in the deep end a bit with this, but thought it would be a good opportunity to learn, not turning out great atm haha

I’m finding that article a bit hard to follow tbh, would it be simpler to use vanilla JS to get the API?

Sure thing. For some reason, it doesn’t show up the same way as in my browser, but hopefully, this will be clear enough to go on.

https://codepen.io/KUBIX90/pen/WEPMwe

How should I go about solving this? Do I need to set up a dev server, as shown in the video below?

Great, I’ll get to work on setting that up. Thanks for your help, much appreciated.

You should know that setting up your own dev server won’t solve the problem on your users’ machines. They’ll have the same CORS problem (cross-origin requests are clearly disabled, that’s why you’re getting the error!).

You need a work-around.

I tried to set up a pen (cut-down version of your code): https://codepen.io/Astravagrant/pen/mMvxyd

It creates a script tag that calls the URL and passes the response to the callback function…

However, one problem is, you can’t make JSONP calls to HTTP servers from inside codepen.

The other problem is, the server you’re trying to connect to doesn’t return the right MIME type for JSONP calls (at least, not from that endpoint/URL). You can JSON back, but you need JS back (application/json vs application/javscript). You can’t control this, it’s server-side configuration.

The server owner doesn’t want people using its resources externally. That’s the point of CORS. You can fake it with middle-man servers pretending to be part of the domain serving the resource, but you can’t get between all of your users and the server! This isn’t my area of expertise, but it seems like you’re trying to do something that is explicitly difficult or impossible to do without the agreement of the server owner.

Sorry.

To explain a bit better, you’re running, say ‘kubix.com’, which makes a request to ‘quotesondesign.com’ (QOD.com), but QOD.com doesn’t want anyone but visitors to its own domain getting any responses (i.e. it disables CORS). You set up a local dev server with domain ‘quotesondesign.com’ configured in local DNS and make requests to qod.com, qod.com says’ yeah fine, that’s the right domain’ and you get responses. As soon as you ship your code to a real webserver (e.g. kubix.com), this fails, because CORS.

Works everywhere just fine: here is on jsfiddle.

1 Like

Ah, sorry rmdawson, after looking at noyb’s code, I re-read the messages above. I’d missed the switch to HTTPS. Damn. Could have saved some time there! I blame working for 12 straight days without a break.

Hopefully the points I raised above still are useful in other contexts, but at this rate, I’m not banking on it. I’m going to get comfy.

1 Like

Thanks for the further information above.

Just to clarify, I’m looking to eventually host this project on my portfolio site through GitHub pages once It’s complete (don’t like codepen). A lot of the projects to come involve using API’s, so I suppose my question is how do I complete projects using API’s, and then ensure that they work properly on Github pages for others to view.

better to post new question, so the answer can help others, too :wink:

Fair enough! Was just a bit wary of clogging up the forum with threads. I’ll get something posted up.