I have a component class calling my service method:
const requestLogin = (username, password) => {
let response = authService.login(username, password);
console.log("test1");
console.log(response);
console.log("test2");
}
And here is the service method that making request to backend:
export function login(username, password) {
axios({
method: "post",
url: "http://localhost:8080/auth/login",
data: {username: username, password: password}
}).then(res => {
if (!res.ok) {
throw Error('Network Error'); //error from axios
}
return res.json();
}).catch(err => {
console.log(err.message) //to display the error to your user just use the useState to define your error
})
}
After that execution, actually backend is responding correctly and I see jwtToken from backend in Network tab, but in console I only see:
Where am I doing wrong ? I just want to check if the jwtToken is coming successfully and response code is 200 then I want to navigate to another page but why my debug console outputs showing this?
2
Answers
Api calls are asynchronous by nature. If you want to wait for the response use:
Other than that, are you sure your response has ok attribute in it? because res.ok could be undefined and !res.ok clause will be true. SuccessfullCallback is a function that will run when response code is 200, there shouldn’t be a case where you need to check for invalid response in successCallback function.
The response of
axios
does not contain a property calledok
. The response schema can be found here.The other issue with your code is that your
login
function does not return anything currently, which is why that just printsundefined
.Depending on what you want to do, you can either return the call of the
axios
requestreturn axios({...})
which will give you aPromise
back that you can handle withthen/catch
, or you can define yourlogin
function as anasync
function and useawait
and return the response that way.Either way you need to handle the returning
Promise
from yourlogin
function.