wp-json API 在带有 React 和 None 的后期编辑中返回 401



我正在尝试使用 React 在 WordPress 中创建一个管理页面,允许用户管理帖子内容。我已经成功地在 react 中创建了一个删除方法以使用 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();
})
}

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

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

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

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

希望这有帮助!

你必须

axios.defaults.headers.common['X-WP-Nonce'] = wpApiSettings.nonce; 

在发送请求之前。最佳做法是在构造函数中设置它。

并始终记住在发送对象之前使用 QS 对其进行序列化。

相关内容

最新更新