@bcworkz Thanks for confirming.
Creating nonce and registering rest routes
add_action('admin_enqueue_scripts','addScripts');
function addScripts() {
wp_enqueue_script('axios', 'https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js', 1);
wp_enqueue_script('vue',plugin_dir_url(__FILE__).'MiddleMan.js',1);
fp_localize_script();
}
function fp_localize_script()
{
$plugin_config = array(
'allowedOrigin' => $_SERVER['SERVER_NAME'],
'allowedDevOrigin' => $_SERVER['HTTP_HOST'],
'ajaxurl' => admin_url('admin-ajax.php', 'relative'),
'nonce'=> wp_create_nonce('wp_rest'),
);
wp_localize_script( 'vue', 'fpPluginConfig', $plugin_config );
}
function my_customize_rest_cors() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Headers: X-WP-NONCE, Content-Type');
return $value;
} );
}
add_action( 'rest_api_init', 'my_customize_rest_cors', 15 );
add_action( 'rest_api_init', function () {
register_rest_route(
'fpwp',
'posts/',
array(
'methods' => 'POST',
'permission_callback' => function () {
return current_user_can('edit_others_posts');
},
'callback' => 'newEndPointCallback'
) );
register_rest_route(
'fpwp',
'authmeth/',
array(
'methods' => 'POST',
'permission_callback' => function () {
return current_user_can('edit_others_posts');
},
'callback' => 'accessFirstPageCallback'
));
} );
I console.log this nonce created here and copy that to vue instance from which the api calls are made.
The vue js code goes as below.
async getAccessToken () {
let headers = {
'X-WP-NONCE': the_actual_nonce_value_which_was_copied
};
try {
const response = await Axios.post('https://localhost/wordpress/wp-json/fpwp/authmeth/', {}, { headers: headers });
return response;
} catch (error) {
throw error;
}
}
The reason why I was doubting the origin issue was because the nonce was validated perfectly when I enqueued the vue js build files into the wordpress plugin. Only when the api call was made from a different origin, the nonce was invalid.
-
This reply was modified 4 years, 11 months ago by dazz17.