Random Quote Generator CORS issue

Random Quote Generator CORS issue
0

#1

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
		});
	});
});

#2

Try using this for your url:

https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1

You needed the https:// and did not need the _jsonp=mycallback

You will need to delete data.shift() if you use the the url I show above…


#4

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
		});
	});
});

#5

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.


#6

If you take a look at your console, you will see an error on this line:

$("#quote-title").text(post.title);

You are referring to a post object. In your current version you post above, your anonymous function should have a post parameter. Once you do this, put a console.log(post), so you can see that you are getting an array of one object and not an object. You need to reference the array’s first element (which is the object).

There are a couple of ways two get the object you seek to use the rest of your existing code:

#1) You could assign post.shift() back to post

post = post.shift();

#2) You could assign the first element of post back to post

post = post[0];

#7

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.


#8

Can you post a link to your complete code? Maybe there is something else going on that I can not see.


#9

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?


#10

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


#11

Since you are trying to run the page from your desktop, this error makes sense now. CORS requires a webserver, so if you ran your own local webserver and accessed the page from it, it would work.

Your Codepen as written has all local references to files and not absolute, so Codepen can not access those local files. See the console for many many error messages in your Codepen.


#12

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


#13

Yes, that is an option for developing locally for testing out your code.


#14

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


#15

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.


#16

So Codepen is on their allowed list? I used Codepen with the suggestions I made to the OP and it works fine without using JSONP.


#17

Works everywhere just fine: here is on jsfiddle.


#18

That is what I was thinking too.


#19

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.


#20

No worries. 12 days straight will do that.


#21

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.