Search code examples
ember.jsember-data

Returning 401 Unauthorized even the adapter is created


The request returned a 401 Unauthorized for GET /foos. From the guide that I read earlier, https://guides.emberjs.com/release/models/customizing-adapters/ it stated that the host name must defined

Question: WHy is it returning 401?

My app/adapters/application.js

  import JSONAPIAdapter from '@ember-data/adapter/json-api';

  export default class ApplicationAdapter extends JSONAPIAdapter {
    namespace = 'api/v1';
    host = 'https://someUrl.com';
  }

and my app/models/foo.js is

import Model, { attr } from '@ember-data/model';

export default class FoowModel extends Model {
  @attr('string') landmark;
};

and my app/routes/welcome.js is

import Route from '@ember/routing/route';

export default class WelcomeRoute extends Route {
  model() {
    return this.store.findAll('foo');
  }
}

Solution

  • 401 Unauthorized means that your are not allowed to get this url , you have to authenticate before sending your request, it depends on what kind of authentication you are using, if you are using OAuth 2.0, JWT for example, in your adapter you have to add

    export default class ApplicationAdapter extends JSONAPIAdapter {
        namespace = 'api/v1';
        host = 'https://someUrl.com';
        headers = {
            'Authorization': 'Bearer yourTokenHereGotFromYourApiWhenLogin',
        };
    }