`fetch`请求没有显示所需的结果,`ajax`请求

时间:2016-06-28 13:38:24

标签: javascript jquery ajax post fetch

我有两个请求,一个是ajax,另一个是fetch,是继承人。

如果我使用fetch将数据发布到与ajax完全相同的(黑盒子)API,则结果会有所不同。

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

结果:

enter image description here

我的主要问题是我需要jwt返回的Ajax变量,但在Fetch实现中,我没有在响应中获得该变量。

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

请务必根据需要设置Accept和/或Content-Type标头。 $.post会根据您提供的数据对这些进行最佳猜测。 fetch api将它留给用户。

相关问题