Basic authentication not working for WP API with I

2019-07-25 13:42发布

问题:

I got this Ionic project going where I make use of the WP API. Now in my app I want the user to be able to submit a post and that the data gets saved to the WP DB. I am trying to achieve this by having my app automatically authenticate as 1 user for everyone. Base of the following documentation, I installed the Basic Auth Plugin. I also installed angular-base64. Hooked everything up and run the app but I am still getting a 401 (unauthorised).

Following the WP API V2 documentation on CRUD the api route to use to post anything is the following -> POST /wp-json/wp/v2/posts to create a new Post

Part of my HTML code:

<div class="padding">
        <textarea class="customTextarea" name="question" id="" cols="30" rows="30" 
        placeholder="Add Question Here" ng-model="question"></textarea>

        <button ng-click="save()">Submit</button>
    </div>

Part of my controller code:

.controller('AddQuestionCtrl', function($scope, $http, $base64){
    $scope.save = function(){
        console.log('SAVE');
        var url = 'http://XXXXX/wp-json/wp/v2/posts';
        var username = 'XXXX';
        var psw2 = 'XXXXX';

        $http.post(url, {question: $scope.question},{
            headers:{
                'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
                'Authorization' : 'Basic' + $base64.encode(username + ':' + psw2),
                'Access-Control-Allow-Origin': '*' 
            }
        }).then(function(response){
            $scope.result = response;
            console.log('The data has been saved to DB', $scope.result);
        });


    }

})

Please can someone help me out. What have I forgotten of done wrong.

回答1:

I think it may be as simple as you're missing a space after Basic:

'Authorization' : 'Basic ' + $base64.encode(username + ':' + psw2),