• AndrwCris

    (@andrwcris)


    Hi,

    I’m learning about the REST API but have come up against an issue when trying to delete a post. The code I’m using is.

    PHP

    wp_localize_script('main-university-js', 'universityData', array(
            'root_url' => get_site_url(),
            'nonce' => wp_create_nonce('wp-rest') //secret value created every time you log in and can be used for authentication to alter content 
        ));

    JS

    deleteNote() {
            $.ajax({
                beforeSend: (xhr) => {
                    //this picks up value set in functions.php to allow authentication to be passed through with function so WP knows to allow deletion.
                    
                    xhr.setRequestHeader('X-WP-Nonce', universityData.nonce);
                },
                url: universityData.root_url + '/wp-json/wp/v2/note/94', //fixed value whilst testing
                type: 'DELETE',
                success: (response) => {
                    console.log("Congrats");
                    console.log(response);
                },
                error: (response) => {
                    console.log("Sorry");
                    console.log(response);
                }
            });
            alert(universityData.nonce);
        }
    
    }

    I added the alert to see if the data was getting passed in correctly and that data matches the value in the page source. I’ve tried clearing cookies, using different browsers (inc. incognito) and restarting the local dev environment but not really sure what else to try or where I’m going wrong.

    The error I’m getting the console is

    responseJSON
    :
    code
    :
    "rest_cookie_invalid_nonce"
    data
    :
    {status: 403}
    message
    :
    "Cookie nonce is invalid"
    __proto__
    :
    Object
    responseText
    :
    "{"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid","data":{"status":403}}

    and if I visted https://fictional-university.local/wp-json/wp/v2/users/me?_wpnonce=0c89bdd7f8 (correct nonce at the time) then I get the following on the page

    {"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid","data":{"status":403}}

    Thanks

    Andrew

Viewing 1 replies (of 1 total)
  • Thread Starter AndrwCris

    (@andrwcris)

    Actually just realised it was a typo … wp_rest not wp-rest!

    'nonce' => wp_create_nonce('wp_rest')

    NOT as I had it…

    'nonce' => wp_create_nonce('wp-rest')

    • This reply was modified 7 years ago by AndrwCris.
Viewing 1 replies (of 1 total)
  • The topic ‘WP REST API Nonce check failing with 403 error’ is closed to new replies.