2016-06-28 118 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將其留給用戶。