WP_REST_API Nonce not working.
-
So i am trying to Add authorization to my custom rest endpoint
here is some code:
add_action('rest_api_init', function() { register_rest_route('posts_bank/v1', '/import_posts/(?P<id>\d+)', array( 'methods' => 'POST', 'callback' => array(&$this , 'import_posts'), )); });
wp_register_script('posts-bank-main', plugins_url( '/templates/js/main.js', __FILE__ )); wp_register_style('posts-bank-main', plugins_url( '/templates/css/main.css', __FILE__ )); wp_localize_script('posts-bank-main', 'wpApiSettings', array( 'nonce' => wp_create_nonce('import_posts') )); wp_enqueue_script('admin-widgets'); wp_enqueue_script('posts-bank-main'); wp_enqueue_style('posts-bank-main');
And heres the JS:
var url = "https://localhost/?rest_route=/posts_bank/v1/import_posts/1"; $.ajax({ url: url, method: "POST", beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); }, data: {"_nonce": wpApiSettings.nonce}, success: (response) => { alert(1); } });
But wordpress responds with:
{code: "rest_cookie_invalid_nonce", message: "Cookie nonce is invalid", data: {status: 403}}
How to resolve this?
Thanks!
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘WP_REST_API Nonce not working.’ is closed to new replies.