我有一个自定义的帖子类型,叫做pronews
. 我在注册了show_in_rest
已启用。我正在使用WordPress 5.5。
然后我有了这个代码:
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 );
} );
在控制台中,我首先得到:{…}
_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
但是主干API的请求是错误的urlRoot
:XHRGET https://localhost/wp-json/wp/v2/posts/2454 [HTTP/1.1 404 Not Found 340ms]
rest_post_invalid_id
对于调试,第二个HTTP请求的结果使用window.fetch
, 显示自定义帖子类型的终结点存在并且可以正常工作:XHRGET https://localhost/wp-json/wp/v2/pronews/2454 [HTTP/1.1 200 OK 587ms]
2454