URL issue retrieving Custom Post Types using Backbone JS API
I have a Custom Post Type called pronews
. I registered it with show_in_rest
enabled. I'm using WordPress 5.5.
I then have this code:
export const ProPost = wp.api.models.Post.extend( {
urlRoot: wpApiSettings.root + 'wp/v2/pronews',
defaults: {
type: 'pronews',
},
} );
export const ProPosts = wp.api.collections.Posts.extend( {
url: wpApiSettings.root + 'wp/v2/pronews',
model: ProPost,
} );
const post = new ProPost( {id: 2454} );
console.log( post );
console.log( 'post urlRoot:' + post.urlRoot );
console.log( 'post url:' + post.url );
post.fetch().then( ( response ) = {
console.log( response )
}, ( why ) = {
console.log( why.responseJSON.code )
} );
// Double check that the endpoint is functionnal
fetch( wpApiSettings.root + 'wp/v2/pronews/2454' )
.then( blob = blob.json() )
.then( ( response ) = {
console.log( response.id );
} );
In the console I first get:
{…}
_changing: false
_pending: false
_previousAttributes: Object { type: pronews, id: 2454 }
attributes: Object { type: pronews, id: 2454 }
changed: Object { }
cid: c3
id: 2454
prototype: Object { urlRoot: https://localhost/wp-json/wp/v2/pronews, defaults: {…}, constructor: i()
}
ProNews.js:17:9
post urlRoot:https://localhost/wp-json/wp/v2/pronews ProNews.js:18:9
post url:function(){var e=a.get(apiRoot)+a.get(versionString)+(me===i?users/me:i);return _.isUndefined(this.get(id))||(e+=/+this.get(id)),e} ProNews.js:19:9
But the Backbone API's request is done to the wrong urlRoot
:
XHRGET https://localhost/wp-json/wp/v2/posts/2454 [HTTP/1.1 404 Not Found 340ms]
rest_post_invalid_id
For debugging, the result of the second HTTP Request using window.fetch
, shows that the endpoint for the Custom Post Type exists and is functional:
XHRGET https://localhost/wp-json/wp/v2/pronews/2454 [HTTP/1.1 200 OK 587ms]
2454
Topic backbone rest-api plugin-development custom-post-types Wordpress javascript
Category Web