在大部分狀況下,後臺請求異常時,都會返回對應的狀態碼,400,404,500等等,可是,如今一些後端設計返回response.status都爲200,經過code或者status來判斷請求是否正確,從而開始了這個坑的攻克。javascript
首先是發現了response.json()是一個promise,因此在處理的時候確定是使用promise的方式來處理:java
const res = response.json(); res.then(data => { if (data.status === 3) { const errortext = codeMessage[401]; const error = new Error(errortext); error.name = response.status; error.response = response; throw error; } return data; });
剛開始覺得這樣處理就能夠了,沒有return
這個promise
,因此在models裏call了一個undefined,至關鬱悶,因此開始走了一些歧路:
一直想着返回值是個Promise,因此就想着本身造一個json
const res = response.json(); const promiseRes = res.then(data => { const promise = new Promise((resolve) => { if (data.status === 3 { message.error('登陸狀態失效,請從新登陸', 3, () => { window.g_app._store.dispatch({ type: 'login/logout', }); }); } resolve(data); }) return promise; }) return promiseRes;
雖然好像是解決了問題,可是又是resolve又是好幾層的return,怎麼看都以爲彆扭,可是因爲項目忙就將就用了一段時間。
後來意識到了res自己就是一個promis,因此直接去掉了那一層彆扭的promis(PS: 內心感受各類舒暢)後端
const res = response.json(); return res.then(data => { if (data.status === 3) { const errortext = codeMessage[401]; const error = new Error(errortext); error.name = response.status; error.response = response; throw error; } return data; });
這個問題產生於後臺請求報常規錯誤時產生的,當後臺返回狀態碼爲500或者401後,進入catch,會發現antd pro 返回個啥,return;
???啥,這不就是返回了一個undefined麼,而後致使了代碼報undefined的錯誤,更離譜的是,是401的時候,跳轉登陸,從新登陸後,出錯的列表頁,列表仍是爲空,甚至沒有從新請求接口。promise
解決辦法一: 使用神奇的 ...antd
put({ type: '', payload: { ...response } }); // 一樣的在reduce裏面也須要作相應的處理 return { ...state, some: { ...payload } }
解決辦法二:暴力解決,多是一個不是辦法的辦法,可是好像有點卵用app
return;
改爲return e;
fetch
因此求一個更好的解決辦法,拜謝!!!url
1.當body的值是一個字符串時:spa
newOptions.body = JSON.stringify(newOptions.body); // 當爲字符串的時候會有兩對引號 newOptions.body = typeof newOptions.body !== 'string' ? JSON.stringify(newOptions.body) : newOptions.body; // 因此加一個判斷
2.修改總體請求頭'Content-Type': 'application/x-www-form-urlencoded'
僅僅須要改爲qs的stringify: s=1&a=2
import { stringify } from 'qs'; /* * 此處省略 */ newOptions.body = typeof newOptions.body !== 'string' ? stringify(newOptions.body) : newOptions.body;