Javascript `fetch`request未显示所需结果,`ajax`request显示所需结果

Javascript `fetch`request未显示所需结果,`ajax`request显示所需结果,javascript,jquery,ajax,post,fetch,Javascript,Jquery,Ajax,Post,Fetch,我有两个请求,一个是ajax,另一个是fetch,后续的请求 如果我使用fetch将数据发布到与ajax完全相同的(blackbox)API,结果会有所不同 Ajax $.post(this.config.baseUrl + this.config.loginUrl, { username:this.username, password:this.password }) .done(data => {debugger;}); // result: {"jwt":"eyJ0eX

我有两个请求,一个是
ajax
,另一个是
fetch
,后续的请求

如果我使用
fetch
将数据发布到与
ajax
完全相同的(blackbox)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;
  });
this.http.fetch(this.config.baseUrl+this.config.loginUrl{
方法:“post”,
正文:json({
用户名:this.username,
密码:这个是密码
})
})
。然后(响应=>{
//设x=response.json();
//如果取消对上述内容的注释,则会出现错误:
//未定义:1未捕获(承诺中)语法错误:JSON中位置0处的意外标记<
调试器;
});
结果:

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


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

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

确保根据需要设置
接受
和/或
内容类型
标题
$。post
根据您提供的数据对这些进行最佳猜测。fetch api将其留给用户。

很抱歉,我将更新此问题。如果我这样做,就会弹出:
undefined:1 Uncaught(in promise)SyntaxError:Unexpected token
response.text()。然后(t=>console.log(t))output?谢谢@robertklep,是HTML。似乎
Ajax
只是忽略了HTML,而
Fetch
没有告诉我内容类型。这是一个服务器端问题。我将召集该团队进行修复:)您确定这不是身份验证失败吗?
$.post
调用发送一个格式为
username=hello&password=world
的正文,而我假设
body:json(…)
会导致
fetch
调用发送一个格式为
{“username”:“hello”,password:“world”}
的正文服务器设置为仅读取其中一种格式。