When attempting to post a comment in my ionic app using the Wordpress api, I encountered error 401 (unauthorized) indicating that the Wordpress api does not recognize me as logged in.
This is the code I am using:
postComment(params?: any) {
let nonce = localStorage.getItem('nonce');
let seq = this.api.post('wp', 'comments', "post="+ params.post+ "&author_name="+params.author_name+"&author="+params.author+"&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f59480819d9a87aa9098949c99c8988c9098949c99b59298994c99db969a98">[email protected]</a>&content=something").share();
seq
.map(res => res.json())
.subscribe(res => {
}, err => {
console.error('ERROR', err);
});
return seq;
}
In my investigation, I found that I need to include the nonce in my request. One suggestion is to use jQuery ajax like this:
.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
}).done( function ( response ) {
});
I am now wondering how to achieve the same thing in typescript. Specifically, how can I implement the beforeSend function with xhr.setRequestHeader in typescript?