mmeridyth
Forum Replies Created
-
That’s great, getting the nonce from the API to the frontend is exactly what I was trying to ask, thanks for your help!
@nr2012
Its good to know that I can get it working with separate code bases.
I want to know how you do an API call from your Vue application and if you always have to have the nonce in the url if its a draft or preview you are trying to see?For instance the call to see one of my projects is – http://content.domain.local/wp-json/wp/v2/projects/?slug=project-one
I’ve made a custom endpoint for this custom post type with all the fields I would like but because it’s a draft post I get a permissions error. It works fine when the project is published. But I want to be able to preview projects before I publish them.
In my Vue application from the examples I’ve seen I need to have a header set to see restricted content –
let url = store.state.apiUrl + 'projects/?slug='+params.slug axios.get(url, { headers: { 'X-WP-Nonce': 'how to get this' } }) .then(response => { // If request is good... console.log(response.data); }) .catch((error) => { console.log('error ' + error); });I’ve been trying to understand the authentication documentation here https://developer.ww.wp.xz.cn/rest-api/using-the-rest-api/authentication/ but I don’t understand how to do it when I can’t get the nonce value for the header because the examples are getting it from a wp_localize_script. When im in my Vue application I don’t have access to anything in my functions.php file (different codebase). So is the only way to authenticate the API call by having in nonce in the API url like your example for previewing changes or is there another way?
Hi @nr2012
Thanks for writing all your thought process here, really helpful. Do you mind if I ask if your WP site and your Vue application were on the same codebase?
For instance my wordpress site is at content.domain.local but my vue application is on another url domain.local and im having issues authenticating because my functions.php file is not in the same codebase and all the examples like this won’t work
wp_localize_script( 'my-script', 'MyScript', array( 'nonce' => wp_create_nonce( 'wp_rest' ), ) );jQuery.ajax( { url: url, data: data, beforeSend: function( request ) { request.setRequestHeader( 'X-WP-Nonce', MyScript.nonce ); }, } )Did you try to get the draft preview working too or just the preview changes button?
Cheers