gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:13:41 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com