I have a little trouble using fetch,
This is javascript code:
function loginJS() {
const login = document.getElementById('login');
const nome = document.getElementById('lnome');
const pass = document.getElementById('lpass');
const item = {
Username: nome.value.trim(),
Password: pass.value.trim()
};
fetch(uri, {
credentials: 'include',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(response => response.json())
.then((res) => {
//trying get the error (this if not work) , 400 is the code for bad request
if (status = 400) {
console.error(''); //HERE I HAVE THE PROBLEM
}
nome.value = '';
pass.value = '';
console.info('Login Success');
window.location.href = url_1;
})
.catch(error => console.error('Unable to Login: ', error));
}
So the problem is getting the bad request from a Web API controller,
If the controller gives a badRequest it has to stop the fetch and not give the 'Login Success' for example
How is this done? and if there are better solutions to get this error (ex: use AJAX instead of fetch).
Any help is welcome
Ps: To warn that this Javascript code and the Web API controller code work normally if there were no badrequests
EDIT
With the respost of using something like a return; i have other problem that is i can't get the 'status' code
.then((res) => {
if (status == 400) {
window.alert('ERRROOORR');
return;
}
else if (status == 200) {
nome.value = '';
email.value = '';
pass.value = '';
window.alert('Register Sucess');
document.getElementById('LoginCheck').click();
} else {
window.alert('Not making sense');
}
})
In the code above it gives the 'Not Making Sense' , how do I get the true value of the status passing the true status to a variable?