[英]Fetch API return json object or response status
我對獲取 API 有點困惑。這是一個簡單的登錄 function
export default class LoginService {
async loginUser(u, p) {
return fetch(API_URL + '/users/authenticate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ 'username': u, 'password': p })
})
.then(response => response.json())
.catch(e => console.log(e))
}
}
當找不到用戶時,在后端返回 400 錯誤請求。 如何返回 json object 或響應狀態? 或者這種做法是錯誤的?
謝謝!
如何返回 json object 或響應狀態?
ok
響應屬性為您提供 HTTP 調用的高級“有效/無效”( fetch
僅拒絕其 promise網絡錯誤,而不是 HTTP 錯誤 - api 中的腳槍,您經常看到人們發生沖突)。
我不會返回響應狀態,我會將其包含在async
function 拋出的錯誤中。我通常這樣做:
async loginUser(u, p) {
return fetch(API_URL + '/users/authenticate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ 'username': u, 'password': p })
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`};
}
return response.json();
}); // Note: No `catch` here!
}
但如果你真的想退貨:
async loginUser(u, p) {
return fetch(API_URL + '/users/authenticate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ 'username': u, 'password': p })
})
.then(response => {
if (!response.ok) {
return {failed: true, status: response.status};
}
return response.json();
})
.catch(e => console.log(e));
}
不過,以這種方式將拒絕轉化為滿足通常不是最佳做法。
.then(res=>{
if(res.ok)
{
return response.json()
}
else{
// return 400 bad request here
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.