我正试图通过wordpress api在我的离子应用中发表评论,但它说错误401(未经授权)意味着Wordpress api认为我没有登录..
我的代码:
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+"&author_email=myemail@gmail.com&content=something").share();
seq
.map(res => res.json())
.subscribe(res => {
}, err => {
console.error('ERROR', err);
});
return seq;
}
在我的研究中,它说我必须发送nonce,我可以这样做:
.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 ) {
});
我怎样才能在打字稿中这样做?如何以打字稿形式放置一个beforeSend函数xhr.setRequestHeader?
答案 0 :(得分:0)
setRequestHeader方法设置与您的请求一起发送的标头。在Ionic / Angular中完成的方法是在requestoptions参数中添加一个头对象:
let opts: RequestOptionsArgs = {};
let headers = new Headers();
headers.append('X-WP-Nonce', nonce);
opts.headers = headers;
return this.http.post(fullPath, requestBody, opts)
.map(this.extractData)
.catch(this.handleError);