-1

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?

Chris Garsonn
  • 717
  • 2
  • 18
  • 32
  • You don't return anything from the `login` method: your return statement is for the *callback to .then*, not for the outer method. You will need to return the axios call and `await` it where you want to use it. There are plenty of resources for this around the web [including the official axios documentation](https://axios-http.com/docs/post_example). – Jared Smith Feb 24 '23 at 13:30

2 Answers2

1

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.

Joxtacy
  • 61
  • 4
0

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.

chuftica
  • 160
  • 8
  • 1
    Note that the OP doesn't actually return the axios call, the return of the `login` method is `undefined` so `await`ing doesn't actually help. – Jared Smith Feb 24 '23 at 13:31