WP Rest API: Using JSONP and Routes with permalinks disabled?

714 Views Asked by At

I am working with the WORDPRESS REST API and Wordpress version 4.8. We have permalinks disabled (security reasons) and thus I am accessing the posts object like so:

https://wordpress-dosstx.c9users.io/?rest_route=/wp/v2/posts

This works fine in Chrome and some versions of IE, but get a failed CORS request message in FireFox, and a few other versions of different browsers.

I thought I'd try and set up the request to use JSONP to get around this restriction. However, since we have permalinks turned off, I am unsure how to write the route. According to the WP API docs, the API natively supports JSONP responses and I'd write something like this:

<script>
function receiveData( data ) {
  // Do something with the data here.
  // For demonstration purposes, we'll simply log it.
  console.log( data );
}
</script>
<script src="https://wordpress-dosstx.c9users.io/?rest_route=/wp/v2/posts?_jsonp=receiveData"></script>

But, since I'm not using permalinks, how would I write the script URL in the script tag? The docs say to write the index route like so:

https://wordpress.org/wp-json/wp/v2/ would become https://wordpress.org/?rest_route=/wp/v2

My attempt to append the jsonP callback function to the post object gives me a 404 not found. Any idea what is the correct way I should be adding the JSONP syntax to the route? My below attempt did not work.

<script src="https://wordpress-dosstx.c9users.io/?rest_route=/wp/v2/posts?_jsonp=receiveData"></script>

JSFIDDLE available for testing: JSFIDDLE

1

There are 1 best solutions below

0
On BEST ANSWER

It looks like you have a typo, an extra ? in the url query string.

Replace:

src="https://wordpress-dosstx.c9users.io/?rest_route=/wp/v2/posts?_jsonp=receiveData"

with:

src="https://wordpress-dosstx.c9users.io/?rest_route=/wp/v2/posts&_jsonp=receiveData"

Make sure to use & to separate multiple parameters in the query string. See e.g. this informative Wikipedia article for more info on that.