javascriptjqueryajaxpostfetch

`fetch` request not showing desired result, `ajax` request does


I have two requests, one with ajax and one with fetch, the successor.

If I post my data with fetch, to the exact same (blackbox) API as ajax, the results are different.

Ajax

$.post(this.config.baseUrl + this.config.loginUrl, {
  username:this.username,
  password:this.password
})
  .done(data => {debugger;});

// result: {"jwt":"eyJ0eX..."}

Fetch

this.http.fetch(this.config.baseUrl + this.config.loginUrl, {
  method: 'post',
  body: json({
      username:this.username, 
      password: this.password
  })
})
  .then(response => {
    // let x = response.json();
    // If I uncomment the above, I get an error:
    // undefined:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
    debugger;
  });

result:

enter image description here

My main problem is that I need the jwt variable that Ajax returns, but in the Fetch implementation I don't get that variable in the response.

I hope one of you can explain to me eighter what I can do to alter the Fetch implementation, or to read the variable which I guess would probably be in the ReadableByteStream, but I'm not sure.


Solution

  • Fetch returns an response which has some attributes and body is the one that you need. The datatype of body on fetch is a ReadableByteStream

    On your case the easiest thing to do is convert it to json and that is quite simple :

    this.http.fetch(this.config.baseUrl + this.config.loginUrl, {
      method: 'post',
      body: json({
          username:this.username, 
          password: this.password
      })
    })
      .then(response => {response.json().jwt});