0

Im currently building a login system using angular 2 framework (ionic). This login have 2 post data which are:

Email Password

I've built the API and ran using postman. Everything is fine. It's returning desired response. But the angular 2 POST doesnt seems to do what it should do. For example this is my request code:

var data = JSON.stringify({email: email, password: password});

this.http.post('https://dev.domain.com/api/login', data)
.subscribe(
        res => {
            console.log(res);
            loading.dismiss();
        },
        err => {
            console.log("Error occured");
            loading.dismiss();
        }
);

Laravel returns 200 response and desired data but Angular 2 is always identifying the response as error. This is my Laravel codes:

public function login(Request $request) {

    $data = $request->json()->all();

    $email = $data['email'];
    $password = $data['password'];
    if (Auth::attempt(['email' => $email, 'password' => $password])) {
        $user = User::where('email', $email)->first();
        return response()->json(['data' => $user])->header('Content-Type', 'application/json');
    } else {
        $returnData = array(
            'status' => 'error',
            'message' => 'An error occurred!'
        );
        return response()->json($returnData, 500)->header('Content-Type', 'application/json');
    }
}

I tried installing CORS plugin. Still seems to not solve this issue.

Can anyone help me on this? Thanks

1 Answer 1

1

Change your HTTP status code From 500 to 200 or leave empty.

return response()->json($returnData, 200)->header('Content-Type', 'application/json');

OR

return response()->json($returnData)->header('Content-Type', 'application/json');
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I wouldn't return a 500 for a failed auth either, at best its a 403. Usually though, you just return it as a 200 as in "the request is a success, nothing failed" but the password is incorrect, so you return the status of error, and handle that in your js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.