简体   繁体   中英

Ember-simple-auth and ember-fetch no authorization in fetch query

I am using ember with ember-simple-auth(1.7.0) for authentication. Here is the application adapter function :

authorize(xhr) {
    let { email, token } = this.get('session.data.authenticated');
    let authData = `Token token="${token}", email="${email}"`;
    xhr.setRequestHeader('Authorization', authData);
  }

When I use ember-fetch(5.1.3) there is no header for authentication :

fetch('/appname/v1/user/count'+count_params).then((response)=>{return response.json()})

The same model do successful emberDS query with the auth info in the header. How can I add the information to the fetch headers ?

EDIT :

This is the service I created to wrap fetch :

import Service from '@ember/service';
import fetch from 'fetch';
import { inject as service} from "@ember/service"

export default Service.extend({
  fetch(url){
    let { email, token } = this.get('session.data.authenticated')
    let authData = `Token token="${token}", email="${email}"`
    return fetch(url,{headers: {'Authorization': authData}}).then(
      (response)=>{return response.json()}
    )
  },
  session: service()
});

You need to create fetch wrapper service and use it, instead of "raw" fetch and boilerplating.

Raw usage possible with headers - https://github.com/github/fetch#post-json

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