Niklas
Niklas

Reputation: 1299

Unable to retrieve access_token with iron-ajax response handler in Polymer

I am using iron-ajax in my Polymer project to login a user. After sending the user details to the database I need to return a token if the login succeeds. However, I am having trouble with the response. It would be great If someone could look over my code and tell me what I am missing.

Currently the console returns me undefined when I output the repos property. Below is the code of my iron-ajax my properties and the function that gets called when a user sends the details. In addition I added what I am trying to return.

<dom-module id="login-form">
  <template>    
    <iron-ajax
      id="requestUser"
      url="http://api.dev/oauth/token"
      handle-as="json"
      method="POST"
      content-type="application/json"
      body='{
        "grant_type": "password",
        "client_id": 2,
        "client_secret": "KyHacYa2Q7DCTVLaDe1RSnvTlTI20CrmYb7FXujb",
        "username": "[email protected]",
        "password": "1111",
        "scope": "*"}'
      last-response="handleResponse"></iron-ajax>

    </template>
    <script>

    Polymer({
      is: 'login-form',
      properties: {
        repos: {
          type: Array
        },
      },

      //On-tap loginTheUser runs
      loginTheUser: function() {
        this.$.requestUser.generateRequest();
      },
      handleResponse: function (data) {
        this.repos = data.details.response;
        console.log(this.repos);
      },

   </script>
</dom-module>

The following is the token i try to get returned:

{
  "token_type": "Bearer",
  "expires_in": 3155673599,
  "access_token": "eyJ0eXAiOiJKV1...",
  "refresh_token": "271VWcUXisybg="
}

Upvotes: 0

Views: 118

Answers (1)

tony19
tony19

Reputation: 138266

<iron-ajax>.lastResponse is actually an Object that represents the last received response from the AJAX request. You could bind that to a property in your markup (it seems repos is the target):

<iron-ajax last-response="{{repos}}">

You were passing a method name, which implies you're actually trying to set a handler for the <iron-ajax>.response event. To do that, you could create an annotated event listener with:

<iron-ajax on-response="handleResponse">

Note that your response handler is incorrectly trying to read data.details when it should be data.detail (where data is a CustomEvent).

Upvotes: 0

Related Questions