简体   繁体   中英

How to use the WP REST API with a custom endpoint using the Javascript library?

I have a custom endpoint which does nothing but return a test string. I can reach that endpoint by navigating to mydomain.com/wp-json/mytools/v1/method/get_user_data and it correctly returns my test string, but, I want to be able to reach that endpoint using Javascript, and, I read that the wp-api handles authentication automatically so I should be able to get a current logged in user with this method.

What I need is to be able to use something like wp.api.mytools.method.get_current_user and get the information for the currently logged in user. Is this even possible?

This is the way I created the endpoint:

    register_rest_route( 'mytools/v1', '/method/(?P<method>[\w]+)', array(
        'methods' => 'GET',
        'callback' => 'invoke_method',
    ));

And this is the invoke_method function:

function invoke_method( WP_REST_Request $request ) {
    return wp_get_current_user();
}

This functionality is already implemented by WordPress at the WP_REST endpoint '.../wp-json/wp/v2/users/me. In addition to the logged-in cookie WP REST authentication requires a nonce specified by a query argument '_wpnonce'. The value of this nonce is generated by calling wp_create_nonce( 'wp_rest' ). A normal WordPress front-end page will include the script .../wp-includes/js/api-request.js. This script will define a global wpApiSettings.nonce which will contain this nonce so you can use the request '.../wp-json/wp/v2/users/me?_wpnonce=' + wpApiSettings.nonce. So, you can use jQuery.get().

jQuery.get(
    '.../wp-json/wp/v2/users/me?_wpnonce=' + wpApiSettings.nonce,
    function( response ) {
        var userData = JSON.parse( response );
    ) }
);

If you only want to get the current user I don't think you need Backbone.js. Backbone.js will synchronise collections and models using CRUD and you are not doing any of this.

Overall, yes, it IS possible.

Specifically, if wp-api if you're referring to the node-wpapi JS library , then yes it does handle authentication. Otherwise, you will need to implement Authentication yourself, using Cookie, Nonce, Basic-Auth or JWT.

For second part, it is definitely possible to use something like wp.api.mytools.method.get_current_user to get information. What you'll need is a client library (node-wpapi), and extend it to include your classes and functions, such as mytools and method .

Hope this helps to clarify

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM