2017-08-12 38 views
1

我想在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"); 
      }); 
    } 

回答

0

嘿,所以我一直有得到這個工作,以及同樣的問題,但故障排除一整天后,修復這一現象實際上是相當簡單的,容易被忽視。

axios.put(wpApiSettings.root + "wp/v2/posts/" + post.id, 
    { headers: {'X-WP-Nonce':wpApiSettings.nonce}}, 
    { title: 'test' }) 

應該

axios.put(wpApiSettings.root + "wp/v2/posts/" + post.id, 
    { title: 'test' }, 
    { headers: {'X-WP-Nonce':wpApiSettings.nonce}}) 

我不能相信我misssed這一點,但標題應該是一個對象,它總是在愛可信的PUT或POST功能的第三個參數。如果你沒有任何數據要傳遞,你也可以使用拋出一個空字符串「」第二個參數。

我沒有意識到參數位置是重要的,但在Axios文檔中,原型是axios.put(url[, data[, config]])。當我們意識到我們將標頭對象放入請求體而不是實際放入標頭時,我發現它和一位朋友已經算出來了。

希望這會有所幫助!