Warm tip: This article is reproduced from serverfault.com, please click

api-路线的处理程序无效

(api - The handler for the route is invalid)

发布于 2020-11-26 17:57:09

我正在尝试使用类在WordPress中创建自定义REST API终结点。我也按照传统方式做过-效果很好。但是,使用类时出现错误The handler for the route is invalid

编码:

class CSS_Ads {

    var $url;
    var $endpointPrefix;
    var $endpointName;

    public function __construct()
    {
        add_action('rest_api_init', array( $this, 'ads_api_route' ) );
    }

    public function ads_api_route() {
        register_rest_route( $this->endpointPrefix, $this->endpointName,
            array(
                'methods'  => 'GET',
                'callback' => 'get_all_ads_api_endpoint'
            )
        );
    }

    public function get_all_ads_api_endpoint($params) {
        // doing my post query and stuff
    }

}

环境:

$ads = new CSS_Ads();
$ads->url = get_site_url();
$ads->endpointPrefix = 'bs/v1';
$ads->endpointName = 'ads';

完整错误:

{"code":"rest_invalid_handler","message":"The handler for the route is invalid","data":{"status":500}}

查询设置为-1,网站上只有一个帖子,所以没关系。

Questioner
Fresz
Viewed
0
Fresz 2020-11-29 06:41:09

这里的问题是回调未到达函数。

使用以下额外功能解决了该问题:

public function __construct()
{
    // Add custom REST API endpoint
    add_action('rest_api_init', __NAMESPACE__ . '\\ads_api_route' );
}

// REST API route
public function ads_api_route() {
    register_rest_route( 'my_endpoint/v1', '/ads',
        array(
            'methods'  => 'GET',
                'callback' => [$this, 'get_all_ads_api_endpoint']
            )
    );
}

function init_rest_api_endpoint() {
    $endpoint = new restAPIendpoint();
    $endpoint->ads_api_route();
}
add_action( 'rest_api_init', 'init_rest_api_endpoint' );

希望这对以后的人有所帮助:)