Expose the REST root URL and a nonce with wp_localize_script(), then call any endpoint from JS.
functions.php
function lotgrafix_enqueue_rest_script() {
wp_enqueue_script( 'lotgrafix-main', get_template_directory_uri() . '/js/main.js', array(), '1.0.0', true );
wp_localize_script( 'lotgrafix-main', 'lotgrafixRest', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' ),
) );
}
add_action( 'wp_enqueue_scripts', 'lotgrafix_enqueue_rest_script' );
main.js
fetch( lotgrafixRest.root + 'wp/v2/posts?per_page=5', {
headers: { 'X-WP-Nonce': lotgrafixRest.nonce },
} )
.then( ( r ) => r.json() )
.then( ( posts ) => console.log( posts ) );