0

I'm trying to make a call to the wp-api.org plugin for Wordpress. I want to show all users, and I want to use cookie authentication. Therefore I need to send a header request as explained on the website like this:

options.beforeSend = function(xhr) {
    xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);

    if (beforeSend) {
        return beforeSend.apply(this, arguments);
    }
};

The following code I am using in my model:

App.UsersRoute = Ember.Route.extend({
  model: function() {
     return Ember.$.ajax({
          url: "http://myurl.com/wp-json/users/",
          type: "GET",
          dataType: "json",
          data: JSON.stringify({}),
          beforeSend:  xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
        });


  }
});

At the moment the site returns this message because the authentication failed, but I am logged in and cookies are set:

[{"code":"json_user_cannot_list","message":"Sorry, you are not allowed to list users."}]
Dhaulagiri
  • 3,281
  • 24
  • 26
Maarten Heideman
  • 545
  • 1
  • 9
  • 18

2 Answers2

1

This should work:

App.UsersRoute = Ember.Route.extend({
  model: function() {
   return Ember.$.ajax({
      url: "http://myurl.com/wp-json/users/",
      type: "GET",
      dataType: "json",
      data: JSON.stringify({}),
      beforeSend:  function(xhr) {
        xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
      }
    });
  }
});
chukcha
  • 115
  • 7
  • this work, but the WP_API_settings is not defined so stil get an error and didn't know how get it work. This has something to do with `wp_localize_script( 'wp-api', 'WP_API_Settings', array( 'root' => esc_url_raw( get_json_url() ), 'nonce' => wp_create_nonce( 'wp_json' ) ) ); ` but don't know how to implement that. – Maarten Heideman Apr 22 '15 at 08:55
  • 1
    Sorry, I'm not familiar with WP so cannot help here – chukcha Apr 22 '15 at 10:27
0

the beforeSend property needs to be a function that is passed xhr, like in your first example, in your second code snippet xhr will be undefined.

Jakeii
  • 1,273
  • 9
  • 16