1

I'm trying to create an app through NativeScript and Angular which will manage the working hours of the employees for a company.

So, I have to set up a login page and there's my problem: I linked a function on the tap of the LOGIN button and, after clicking on it, I send username and password to a service where I'm trying to connect to and end-point (mypath/api/auth.php).

In this php file I set up the DB connection and a SELECT query which receive username and password as a $_POST function. But, now, when I tap on my LOGIN button I got an alert with [Object Object] even if the credentials are right or wrong.

I'm a beginner in both NativeScript and Angular.

My PHP user verification function:

$username = $_POST["username"];
$password = $_POST["password"];
$conn = getDB();
$hash_pwd = hash('sha256', $password);

$stmt = $conn->prepare("SELECT * FROM dipendenti WHERE cod_fiscale=:username AND password=:password");
$stmt->bindParam("username", $username,PDO::PARAM_STR) ;
$stmt->bindParam("password", $hash_pwd,PDO::PARAM_STR) ;
$stmt->execute();
$count=$stmt->rowCount();
$data=$stmt->fetch(PDO::FETCH_OBJ);

closeDB($conn);
return json_encode($data);

My user.service.ts file:

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders, HttpResponse } from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError, map, tap } from "rxjs/operators";

import { Auth } from "./auth.model";
import { Config } from "../config";

@Injectable()
export class AuthService {
    constructor(private http: HttpClient) { }

    login( user: Auth) {
        if(!user.codFiscale || !user.password) {
            return throwError("Devi inserire sia codice fiscale sia la tua password per accedere");
        }
        return this.http.post(Config.apiUrl + 'api/auth.php', 
            JSON.stringify({
                username: user.codFiscale,
                password: user.password
            }),
            { 
                headers: this.getCommonHeaders()
            }).pipe(
                map(response => response),
                catchError(this.handleErrors)
            );
    }

    getCommonHeaders() {
        return {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*"
        }
    }

    handleErrors(error: Response) {
        console.log(JSON.stringify(error));
        return throwError(error);
    }
}

My function triggered on the button tap:

submitLogin() {
        if(this.isLoggingIn) {
            this.authService.login(this.user).subscribe(
                () => {
                    this.router.navigate(["/home"]);
                },
                (exception) => {
                    if(exception.error && exception.error.description) {
                        alert(exception.error.description);
                    } else {
                        alert(exception.error);
                    }
                }
            );
        }
    }

Is there something I have forgotten?

halfer
  • 19,824
  • 17
  • 99
  • 186
Silvia
  • 53
  • 4
  • Try to test your end point with a rest client like POSTMAN, make sure it works. Do not alert the error, log it so it may give you some more information by paring object. – Manoj Jan 10 '20 at 16:29
  • You may also want to look in the network tab of the browser (if Chrome) and examine the request / response details. What you really need to do first is to isolate the problem further down to client vs server, and then go next-level deeper. e.g. is client making the correct call (network tab will show you details)? or is the db connection not good? (adding some server logging can help there) etc. – sarora Jan 10 '20 at 16:40
  • Most of all often people forget to do is, not enabling clear text traffic while using HTTP. Only HTTPS is enabled by default in your app (except if you are running Android 8 or lower). – Manoj Jan 10 '20 at 23:33

1 Answers1

1

i do it in nativescript-vue, maybe you need to adjust for angular. I use axios plugin for that, it works for ns-angular too, i just don't know how to config it on angular... but the code is this:

async submitLogin() {

            const data = {
                email: this.user.email,
                password: this.user.password
            };

            try {
                const res = (await api.post(this.getApiUrl+"/app/services/login.php", data)).data;
                if (res.code === 200){
                    //handle login success
                }
                else if (res.code === 500){
                    //handle login fail
                }
            }
            catch (e) {
                console.error("Connection error: ", e);
            }
        },

where api.post is:

post(url, request, config) {
    return axios.post(url, request, config)
        .then((response) => Promise.resolve(response))
        .catch((error) => Promise.reject(error));
},

Edit: The res.code is a custom response that i send in the response, it's not default!

lucasumberto
  • 134
  • 1
  • 9
  • Hi @lucasumberto, thank you... but what's your `api` variable? – Silvia Jan 13 '20 at 16:27
  • @Silvia, Its a import from the .js file that has my axios functions (post, get, patch and delete); in the login vue file: `import api from "~/shared/api"`; And api.js: `import axios from 'axios'; export default { post(url, request, config) { return axios.post(url, request, config) .then((response) => Promise.resolve(response)) .catch((error) => Promise.reject(error)); } }` i removed the rest of the code due stackoverflow limits. As i said this is in vue logic... but **api is just a import from another file**. – lucasumberto Jan 14 '20 at 17:52