WP REST API创建POST身份验证问题

时间:2016-03-06 作者:Ardend

我在尝试从前端创建帖子时遇到401或403错误。我在前端使用angular,我想使用基本授权。我已将api排队并创建了nonce:

wp_localize_script( \'angular-core\', \'RestAPI\', array( \'url\' => get_bloginfo(\'wpurl\').\'/wp-json/wp/v2/\', \'nonce\' => wp_create_nonce( \'wp_rest\' ) ) );
然后,我将此表单设置为html格式:

<form ng-submit="processForm()">
        <!-- Title -->
        <div id="title_field" class="">
          <label>Title</label>
          <input type="text" name="title" class="" placeholder="Name of item" ng-model="formData.title">

        </div>

        <!-- Submit Button -->
        <button type="submit" class="">
          <span class=""></span> Submit!
        </button>

      </form>
这是我的控制器中的processForm函数:

$scope.formData = {}; //stores input from form above
$scope.processForm = function() {
        console.log(RestAPI.nonce);

        $http({
            method: \'POST\',
            url: \'/wp-json/wp/v2/posts\',
            params: $scope.formData,
            transformRequest: angular.identity,
            headers: { \'Content-Type\': \'multipart/form-data\', \'X-WP-Nonce\': RestAPI.nonce }
        })
        .success(function (result) {
            console.log(\'Success!\');
        }).error(function () {
            console.log(\'Fail!\');
        });
    };
将X-WP-Nonce部分添加到头中会使我从401错误变为403错误,然后它只会告诉我Nonce无效。如果重要的话,在登录到管理面板时,如果我去站点尝试访问用户/我(我知道文档中列出了问题),我只需注销并反复要求登录。也许我误解了现在的用法?

感谢您的帮助!

1 个回复
SO网友:Forest Hoffman

这是一个老问题,但当前的REST API表明X-WP-NONCE 标题应通过beforeSend 回调。以下内容直接来自REST API docs.

.ajax( {
    url: wpApiSettings.root + \'wp/v2/posts/1\',
    method: \'POST\',

    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( \'X-WP-Nonce\', wpApiSettings.nonce );
    },

    data:{
        \'title\' : \'Hello Moon\'
    }
} ).done( function ( response ) {
    console.log( response );
} );
你可以放下headers 属性,并使用contentType 所有物也就是说,如果您使用$.ajax 作用

$scope.formData = {}; //stores input from form above
$scope.processForm = function() {
        console.log(RestAPI.nonce);

    // using $.ajax not $http
    $.ajax({
        method: \'POST\',
        url: \'/wp-json/wp/v2/posts\',
        data: $scope.formData,
        transformRequest: angular.identity,
        contentType: \'multipart/form-data\',
        beforeSend: function( xhr ) {
            xhr.setRequestHeader( \'X-WP-Nonce\', RestAPI.nonce );
        },
        success: function (result) {
            console.log(\'Success!\');
        },
        error: function () {
            console.log(\'Fail!\');
        }
    });
};