Support » Developing with WordPress » WP Rest Api / Ajax POST not working when not logged in

  • Resolved joDelicious

    (@jodelicious)


    Hi !

    Following the WordPress documentation about the Rest Api, i can manage to make an ajax POST working, but only when logged in to WordPress. Here are the basic files shown in the documentation:

    functions.php

    wp_localize_script( 'wp-api', 'wpApiSettings', array(
        'root' => esc_url_raw( rest_url() ),
        'nonce' => wp_create_nonce( 'wp_rest' )
    ) );

    app.js

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

    I’m showing this example as it is presented as an easy one, but it is not working when not logged in. It is always giving me a 401 Unauthorized response / “rest_cannot_create”…

    OK, it needs authentication. But why the hell don’t you provide a working solution within wordpress. I have tried many solutions for months now (OAuth, JWT, …)… there is always something going wrong. Feeling like I’m dumb.

    It really feels like the WordPress solution is not complete. I really encourage the WP team to bring a solution.

    Best regards.
    Johan

    • This topic was modified 3 years, 2 months ago by joDelicious.
    • This topic was modified 3 years, 2 months ago by joDelicious.
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘WP Rest Api / Ajax POST not working when not logged in’ is closed to new replies.