`fetch` 请求未显示所需结果,`ajax` 请求显示

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

我有两个请求,一个是ajax,一个是fetch,继任者。

如果我 post 我的数据与 fetch 完全相同(黑盒)API 与 ajax,结果是不同的。

Ajax

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

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

获取

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;
  });

结果:

我的主要问题是我需要 Ajax returns 的 jwt 变量,但是在 Fetch 实现中我没有在响应中得到那个变量.

我希望你们中的任何一个能向我解释我可以做些什么来改变 Fetch 实现,或者读取我猜想可能在 ReadableByteStream 中的变量,但是我我不确定。

获取 returns 具有某些属性的响应,body 就是您需要的响应。 fetch 中 body 的数据类型是 ReadableByteStream

根据您的情况,最简单的方法是将其转换为 json,这非常简单:

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

请务必根据需要设置 Accept and/or Content-Type headers。 $.post 根据您提供的数据做出最佳猜测。提取 api 留给用户。