最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Using WP-API and SSE not authenticating user ID

programmeradmin2浏览0评论

I am using the wp-api to create a custom endpoint for my data:

add_action( 'rest_api_init', function() {
        register_rest_route( 'mb/v1', '/sse/', array(
                'methods'   => 'get',
                'callback'  => 'mb_sse_data',
                'nonce'     => wp_create_nonce( 'wp_rest' )
        ) );
} );

function mb_sse_data( $request ) {

    // headers to notify SSE
    header( "Content-Type: text/event-stream" );
    header( "Cache-Control: no-cache" );

    // set the variables
    $mb_setting_user_array = wp_get_current_user();

    // Get the current time on server
    $currentTime = date( "H:i:s", current_time('timestamp') );

    // data to return
    echo "data: current_time: " . $currentTime . "\n\n";
    echo "data: user_id: " . $mb_setting_user_array->ID . "\n\n";

    // Send it in a message
    flush();
}

And the javascript to call the SSE:

window.onload = function() {
    var source = new EventSource("wp-json/mb/v1/sse/");

    source.onmessage = function(event) {
        console.log( event.data );
    };
};

Except when I check the output of the user ID I am still getting 0. I understand that when authentication fails it will return the 0 value but I cant quote figure out how to make the above work so I can get the user ID.

发布评论

评论列表(0)

  1. 暂无评论