I'm a bit stuck with the fetch API. This is a simple Login 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))
}
}
When user is not found the in the backend return 400 bad request. How can I return the json object or the response status? Or maybe this practice is wrong?
Thank you!
How can I return the json object or the response status?
The ok
response property gives you the high-level "worked/didn't work" for the HTTP call ( fetch
only rejects its promise on network errors, not HTTP errors — a footgun in the api you constantly see people falling afoul of).
I wouldn't return the response status, I'd include it in an error thrown by the async
function. I typically do that like this:
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!
}
But if you really want to return it:
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));
}
Turning rejections into fulfilments that way is generally not best practice, though.
.then(res=>{
if(res.ok)
{
return response.json()
}
else{
// return 400 bad request here
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.