I am using the latest, WP-API and the recommended Basic Auth, to test adding a post to WP from remote.
I have Access Headers opened up on the WP side:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization, Content-Type");
When I submit a Get request to: http://sandbox.ravennainteractive.com/wp-json/wp/v2/posts the call easily authenticates and returns the Hello World Post.
When I submit a Post request to the same url. I get an error. Here is my jquery ajax call:
$('#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;
});
The response is Failed to load resource: the server responded with a status of 403 (Forbidden)
Array[0]responseText: “[{“code”:”rest_forbidden”,”message”:”You don’t have permission to do this.”,”data”:{“status”:403}}]”
If run this block of code, removing unnecessary extras the query works and returns the Hello World post.
$('#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;
});
How can I solve this?