2016-06-28 121 views
1

我有两个请求,一个是ajax,另一个是fetch,它是继任者。`fetch`请求不显示想要的结果,`ajax`请求确实有

如果我将我的数据与fetch一起发布到与ajax完全相同的(blackbox)API,结果会有所不同。

阿贾克斯

$.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中的变量,但我不确定。

+1

'response.text()。then(t => console.log(t))'output? – robertklep

+0

谢谢@robertklep,它是HTML。看起来'Ajax'只是忽略了HTML,而'Fetch'没有告诉我内容类型。这是一个服务器端问题。我打算给这个团队打电话来解决:) – Randy

+0

你确定这不是一个认证失败吗? '$ .post'调用发送格式为'username = hello&password = world'的主体,而我假设'body:json(...)'引起'fetch'调用发送格式为'{“username的主体“:”你好,“密码”:“世界”}'我假设(除非你有非常强大的服务器端代码)服务器设置为只读取其中的一种格式 – apsillers

回答

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

对不起,我要更新的问题。如果我这样做,这会弹出:'未定义:1未捕获(承诺)SyntaxError:意外的标记<在JSON在位置0' – Randy

0

一定要设置Accept和/或Content-Type头如所须。 $.post根据您提供的数据对这些进行了最佳猜测。提取api将其留给用户。