我想在WordPress創建一個管理頁面與之反應,使用戶可以管理的文章內容。我已經成功地創建了一個刪除方法來處理API,但是我很難讓更新工作。WP-JSON API上編輯後返回401反應,現時
// plugin_file.php
add_action('admin_enqueue_scripts', function() {
wp_localize_script('tfw-js', 'wpApiSettings', [
'root' => esc_url_raw(rest_url()),
'nonce' => wp_create_nonce('wp_rest')
]);
});
上面的代碼轉儲靠近我的頁面
<script type='text/javascript'>
/* <![CDATA[ */
var wpApiSettings = {"root":"http:website.com\/wp-
json\/","nonce":"9eb4c99f2c"};
/* ]]> */
</script>
這裏是按預期工作
deletePost(post) {
var _this = this;
this.serverRequest =
axios
.delete(wpApiSettings.root + "wp/v2/posts/" + post.id, {
headers: {'X-WP-Nonce': wpApiSettings.nonce},
})
.then(function(result) {
_this.updatePostList();
})
}
但是我更新的方法刪除方法的底部這個目的,使用了與刪除相同的隨機數密鑰返回401未授權。我不確定,如果使用相同的密鑰是正確的做法,但管理員-ajax.php使用相同隨機數的關鍵,所以我猜測它是。即返回
{"code":"rest_cannot_edit","message":"Sorry, you are not allowed to edit this post.","data":{"status":401}}
我寧願不使用額外的插件來管理這個
updatePost(post) {
var _this = this;
this.serverRequest =
axios
.put(wpApiSettings.root + "wp/v2/posts/" + post.id, {
headers: {'X-WP-Nonce':wpApiSettings.nonce},
data : {
title: 'test'
}
})
.then(function(result) {
_this.updatePostList();
})
}
錯誤。
謝謝!
更新:
我得到這個很容易使用jQuery工作。對我來說這不是什麼大問題,因爲我只是想學習React。仍然好奇,如果任何人可以填補我爲什麼axios不工作與完全相同的標題&發佈數據。我目前的解決方案:
updatePost(post) {
var _this = this;
jQuery.ajax({
type: "POST",
url: wpApiSettings.root + "wp/v2/posts/" + post.id,
data: {
"title": 'test',
},
beforeSend: function(xhr) {
xhr.setRequestHeader("X-WP-Nonce", wpApiSettings.nonce);
}
}).done(function(response) {
_this.updatePostList();
})
.fail(function() {
alert("error");
});
}