json - wp-json API 在使用 React 和 nonce 进行编辑后返回 401

标签 json wordpress reactjs axios

我正在尝试使用 React 在 WordPress 中创建一个管理页面,允许用户管理帖子内容。我已经成功创建了一个删除方法来响应 API,但我在更新工作时遇到困难。

// 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();

            })
  }

但是我的更新方法使用与删除相同的随机数 key 返回 401 未经授权。我不确定使用相同的 key 是否是正确的方法,但 admin-ajax.php 使用相同的随机数 key ,所以我猜测是的。

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();
        })
}

返回错误

{"code":"rest_cannot_edit","message":"Sorry, you are not allowed to edit this post.","data":{"status":401}}

我不想使用额外的插件来管理它。

谢谢!

更新:

我使用 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" );
          });
  }

最佳答案

嘿,我在完成这项工作时也遇到了同样的问题,但经过一整天的故障排除后,解决这个问题实际上相当简单,而且很容易被忽视。

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}})

我不敢相信我错过了这一点,但 header 应该位于一个对象中,该对象始终是 Axios 中 PUT 或 POST 函数的第三个参数。如果您没有任何要作为第二个参数传递的数据,您也可以使用抛出空字符串 ''。

我没有意识到参数位置很重要,但在 Axios 文档中,原型(prototype)是 axios.put(url[, data[, config]])。当我们意识到我们将 header 对象放入请求正文而不是实际将其放入 header 时,我和 friend 一起弄清楚了。

希望这有帮助!

关于json - wp-json API 在使用 React 和 nonce 进行编辑后返回 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45650729/

相关文章:

javascript 向json中添加数据

javascript - react native 警告 : Cannot update during an existing state transition (such as within `render` )

javascript - 在 React Component 的状态中渲染一个对象的属性,在数组中

json - 将 JSON 数据从 DocumentDB(或 CosmosDB)移动到 Azure Data Lake

c# - 将 JSON 对象转换为 C# 对象

php - OOP PHP - JSON 编码的对象

css - 接触形式的 float 形式

php - Wordpress Woocommerce - 使用 update_post_meta 添加产品属性

javascript - WordPress:向古腾堡组 block 添加自定义样式

javascript - 解决Twilio “Uncaught (in promise) t: Error while setting LastConsumedMessageIndex”错误消息