我正在使用最新的WP-API和推荐的基本身份验证,测试从远程向WP添加帖子。
我在WP端打开了访问标头:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization, Content-Type");
当我将Get请求提交给:
http://sandbox.ravennainteractive.com/wp-json/wp/v2/posts 该调用可以轻松验证并返回Hello World帖子。
当我向同一url提交Post请求时。我出错了。下面是我的jquery ajax调用:
$(\'#test-post\').submit(function(e){
e.preventDefault();
var title = $( \'#title\' ).val();
var content = $( \'#content_raw\' ).val();
var postData = {
title: title,
content: content
}
console.log(postData);
$.ajax({
method: \'POST\',
contentType: \'application/json\',
data: postData,
url: sandboxUrl,
beforeSend: function( xhr ) {
xhr.setRequestHeader (\'Authorization\', \'Basic \'+ btoa( \'apiuser\' + \':\' + \'PASSWORD\' ));
},
success: function(data){
console.log(data);
alert(\'Your comment was successfully added\');
},
error: function(data){
console.log(data);
alert(\'There was an error adding your comment\');
}
});
return false;
});
响应加载资源失败:服务器响应状态为403(禁止)
数组[0]响应文本:“[{”code“:”rest\\u禁止“,”message“:”您没有执行此操作的权限“,”data“:{”status“:403}}}]”
如果运行这段代码,删除不必要的额外内容,查询就会工作并返回Hello World帖子。
$(\'#test-post\').submit(function(e){
e.preventDefault();
$.ajax({
method: \'GET\',
url: sandboxUrl,
beforeSend: function( xhr ) {
xhr.setRequestHeader (\'Authorization\', \'Basic \'+ btoa( \'apiuser\' + \':\' + \'PASSWORD\' ));
},
success: function(data){
console.log(data);
alert(\'Your comment was successfully added\');
},
error: function(data){
console.log(data);
alert(\'There was an error adding your comment\');
}
});
return false;
});
我如何解决这个问题?