Backbone with custom rest endpoints
I have created a custom endpoint that returns select user meta data. I am trying to access this endpoint with Backbone. It works as expected in Postman and from my Backbone/javascript script If I have my access check dummied out.
var app2 ={};
app2.Pilot = Backbone.Model.extend({
url: POST_SUBMITTER.root + 'pilotdata/v1/pilot/'
});
app2.pilot = new app2.Pilot();
app2.pilot.fetch(
{data: ({ id: 1 })}
).then(function(){
console.log(app2.pilot)
})
Of course can't have the data hanging out naked. So I implement my access check and I get a status Unauthorized returned as expected. As the nonce is not being returned. But how to set the nonce? from theAverageDev I can up with:
var app2 ={};
app2.Pilot = Backbone.Model.extend({
url: POST_SUBMITTER.root + 'pilotdata/v1/pilot/',
sync: function(){
Backbone.sync('create', this,{
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-NONCE', POST_SUBMITTER.nonce );
},
});
},
});
app2.pilot = new app2.Pilot();
app2.pilot.fetch(
{data: ({ id: 1 })}
).then(function(){
console.log(app2.pilot)
})
And I admit I do not fully understand what that is doing. Overriding sync? However when I do that I get
TypeError: undefined is not an object (evaluating 'app2.pilot.fetch(
{data: ({ id: 1 })}
It appears that overriding sync undefined fetch? What is the best way to use Backbone to pass the nonce?
I think I got it:
var app2 ={};
app2.Pilot = Backbone.Model.extend({
url: POST_SUBMITTER.root + 'pilotdata/v1/pilot/',
});
app2.pilot = new app2.Pilot();
app2.pilot.fetch(
{
beforeSend : function(xhr) {
xhr.setRequestHeader('X-WP-NONCE', POST_SUBMITTER.nonce);
},
data: ({id: 1})
}
).then(function(){
console.log(app2.pilot)
})