Wp-api 2 cookie authentication

So, I have a php page in wordpress (WP-Api 2):

<?php
/**
 * Template Name: WP-Api
 */
add_action("wp_enqueue_scripts", "enqueue_");
function enqueue_() {
    wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );

}
get_header(); ?>

<h1>oi</h1>
<script type="text/javascript">

jQuery.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 );
} );

</script>

I want to run this example but the console says

Read More

Uncaught ReferenceError: wpApiSettings is not defined

What am I doing wrong? Thank you!

Related posts

Leave a Reply

2 comments

  1. Add the following code to functions.php and check if the user already logged in has the capabilities to POST (Create Products, Posting, Upload Media File, etc.)

    /*Cookies Authentication*/
     
         wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
         wp_enqueue_script('wp-api');