You don\'t need 在从外部应用程序使用WordPress REST API之前,登录WordPress仪表板;it\'s irrelevant (当然,除非您在开发过程中希望依赖cookie)。
需要注意的是,您可能已经在服务器端启用了跨源资源共享(CORS),除非您使用的是来自同一源或同一服务器的资源。
您的HTTP响应头401指示已发送未经授权的请求进行处理,您的响应可能是:
{
"code": "rest_cannot_edit",
"message": "Sorry, you are not allowed to edit this post.",
"data": {
"status": 401
}
}
换句话说,你要么
not logged in 您请求的应用程序源于或执行操作的用户
does not have the required permission to perform such an operation.
让我们假设这是第一种情况(未经验证的用户,在正常情况下拥有执行预期操作的所有权利);
显而易见的解决方案是在执行操作之前对用户进行身份验证,正如您所猜测的那样。
现在的问题是:如何通过内置的REST API对WordPress用户进行身份验证?
好消息是:根据您的需求和/或偏好,有一系列选项可供您选择。
下面的代码片段演示了在使用主干时应该如何操作。js公司:
wp.api.loadPromise.done(function() {
// Create a new post
var post = new wp.api.models.Post({
title: \'Posted via REST API\',
content: \'Lorem Ipsum is simply dummy text of the printing and typesetting industry.\',
});
post.save(null, {
success: function(model, response, options) {
console.log(response);
},
error: function(model, response, options) {
console.log(response);
}
});
});
记住排队
wp-api
在您的
functions.php
或插件,如下所示:
/**
* Either of the two can be used to enqueues in-built WP-API;
* not both as any of them enables you achieve the same result: to enqueue wp-api.
* The only difference between them is that one does it independently without any condition
* while the other does so with a condition: to enqueue it as a dependency for your script.
*/
function wp_api() {
// Use the line below to enqueue directly
// (should your code directly reside in your functions.php or plugin).
wp_enqueue_script( \'wp-api\' );
// Use this option instead if you want to enqueue it (wp-api)
// as a dependency for your script (here, located in a js file) so as
// to ensure that your script gets loaded only after wp-api does as it depends on it.
wp_enqueue_script( \'my_script\', \'path/to/my/script\', array( \'wp-api\' ) );
}
add_action( \'init\', \'wp_api\' );
。。。有关在WordPress REST API中使用主干JavaScript客户端的更多详细信息here.