'Javascript: get a BadRequest error from a Web Api .Net 6 using fetch
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?
Solution 1:[1]
After receiving the status code 400, it enters the if statement since it's true. After that its free to leave since you do not return it. Now the code will just plow on through after the if statement whether its true or false.
You should implement something like this:
If (status == 400) {
console.log("400 triggered");
return;
}
You might wanna implement a way to tell your users that something went wrong, since they won't have their consoles open.
REGARDING EDIT
In the code below you assign the returned value to res
.then((res) => {
res most likely stands for response in this case. You should see what res
returns by logging it in the console:
console.log(res)
This should return an object that contains many properties regarding the response status
. Have a look around if you can find the statuscode
. This variable will replace the status
variable.
It will change from this:
if (status == 400) {
To something like this:
if (res.statusCode == 400) {
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |