skip to Main Content

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:
enter image description here

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


  1. Api calls are asynchronous by nature. If you want to wait for the response use:

    let response = await authService.login(username, password); 
    

    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.

    Login or Signup to reply.
  2. The response of axios does not contain a property called ok. 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 prints undefined.

    Depending on what you want to do, you can either return the call of the axios request return axios({...}) which will give you a Promise back that you can handle with then/catch, or you can define your login function as an async function and use await and return the response that way.

    Either way you need to handle the returning Promise from your login function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search