Custom Rest Endpoint: Post/Put/Patch not working

I’m trying to get a custom rest api working to handle some stuff. One part I need to do requires a Post/Put to the API.

But the API-call always goes 404 on me and I have no idea why. I’ve registered a test route as follows

register_rest_route('test/v1', 'test', array(
    'method' => WP_REST_Server::ALLMETHODS,
    'callback' => function () {
        return current_user_can("test_metadata_edit");
    },
    'permission_callback' => function () {
        return true;
    }
));

And I create a nonce for the Post/Put request via an inline script:

wp_add_inline_script("test_script", 'var nonce = "' . wp_create_nonce('wp_rest') . '"');

up until here everything works fine.

Now I try to GET the endpoint, which works. If I supply no nonce at all, it returns false. If a user is logged in and I use the generated nonce either via _wpnonce= or the X-WP-Nonce-header, it returns the correct result for the users capability. But if I try to Post, Put or Patch it always returns a 404 and I have absolutely no clue why. If I create a nonce for a logged out user though, I get a 403 instead.

fetch('/wp-json/test/v1/test', { method: 'GET', headers: {'X-WP-Nonce': '12345'}}) //works
fetch('/wp-json/test/v1/test?_wpnonce=12345', { method: 'GET'}}) //works
fetch('/wp-json/test/v1/test', { method: 'POST', headers: {'X-WP-Nonce': '12345'}) //does not work, 404
fetch('/wp-json/test/v1/test?_wpnonce=12345', { method: 'PUT' }) //also doesn't work, 404

Any ideas as to what is happening?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The 'method' argument for register_rest_route() should be named 'methods'. Because of the typo, the argument is interpreted as it’s default value – 'GET' only.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x