Home > other >  Not receiving the response of 400 using axios
Not receiving the response of 400 using axios

Time:07-11

This code is from my controller,

public function login(Request $request)
{
    $credentials = [
        'email' => $request->email,
        'password' => $request->password
    ];

    if (Auth::attempt($credentials)) {
        $user = Auth::user();
        $success['token'] = $request->user()->createToken('myApp')->plainTextToken;
        $success['name']  = $user->name;

        $response = [
            'success' => true,
            'data' => $success,
            'message' => 'User login successful',
        ];

        return response()->json($response, 200);
    } else {
        $response = [
            'success' => false,
            'message' => 'User login failed',
        ];

        return response()->json($response, 400);
    }
}

This is my axios method,

const login = async () => {
    await axios.post("/api/login", form).then((response) => {
        if (response.data.success) {
            console.log(response.data.message);
        } else {
            console.log(response.data.message);
        }
    });
};

Here in the controller if the condition is false I don't receive any response.If I remove the 400 from return response()->json($response, 400); It gives me a response with 200 code. I don't want it to happen since this is an error. Appreciate it if somebody can point me to the error. Thanks

CodePudding user response:

you need a .catch() here like this:

const login = async () => {
    await axios.post("/api/login", form)
        .then((response) => {
            // Handle API success logic here
            if (response.data.success) {
                console.log(response.data.message);
            } else {
                console.log(response.data.message);
            }
        
    })
    .catch(({message}) => {
        // Error response will always take you here
        console.log(message)
    })    
};

UPDATE

from your controller send the response as 200 for both cases:

if($auth){
   $response = [
      'success' => true,
      'message' => 'User login success',
   ];
        
  return response()->json($response, 200);
} else {
  $response = [
       'success' => false,
       'message' => 'User login failed',
   ];
        
   return response()->json($response, 200);
}

and then make a call as:

const login = async () => {
    await axios.post("/api/login", form)
        .then((response) => {
            // Handle API success logic here
            if (response.data.success) {
                console.log(response.data.message);
            } else {
                console.log(response.data.message);
            }

    })
}

UPDATE #2

in your else part of controller:

else {
        $response = [
            'success' => false,
            'message' => 'User login failed',
        ];

        return response($response["message"], 400);
    }
  • Related