-1

Been trying to make a simple Login page using PHP(backend) and Angular(frontend)

Here is my login.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams} from '@angular/common/http';

    import { User } from '../shared/user.model';
    import { Observable, throwError } from 'rxjs';
    import { map, catchError } from 'rxjs/operators'
    import { environment } from 'src/environments/environment';

    @Injectable({
        providedIn:'root'
    })


    export class LoginService{

        loggedUser: User;

        constructor(private http: HttpClient){}

        loginUser(username:string, password:string){
            const body = {
                'username':username,
                'password':password
            }
            const user = JSON.stringify(body);
            console.log(user);
            return this.http.post(
                environment.url+'login.php',
                user,
                {responseType: 'text'}
            ).pipe(map((res) => {
                console.log(res);
                return res;
            }),(err) =>{
                catchError(this.handleError);
                console.log(this.http.post);
                return err;
            }
            );
        }

        handleError(errorResponse:HttpErrorResponse){
            console.log(errorResponse);
            return throwError("Something Went Wrong");
        }
            
    }

login.component.ts which interact with the webpage:

    import { Component, OnInit } from '@angular/core';
    import { LoginService } from './login.service';
    import { NgForm } from '@angular/forms';
    import { Router } from '@angular/router';
    import { Observable } from 'rxjs';

    @Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {

    constructor(private loginService:LoginService, private router: Router) { }

    onSubmit(form: NgForm){

        console.log("button clicked");

        if(form.invalid){
        return;
        }

        const username = form.value.username;
        const password = form.value.password;

        let authObs: Observable<any>;

        authObs = this.loginService.loginUser(username,password);

        authObs.subscribe(
        resData => {
            console.log(resData);
            this.router.navigate(['/calibration']);
        },
        errorMessage => {
            console.log(errorMessage);
        }
        );

    }

    ngOnInit(): void {
    }  
    }

The login.php

    <?php
        session_start();
        require_once("connection.php");

        $data = file_get_contents('php://input');
        $obj = (array)json_decode($data);
        try  
        {  
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
            if(isset($data))  
            {     
                    $query = "SELECT * FROM user_master WHERE username = :username AND password = :password";  
                    $statement = $conn->prepare($query);

                    $statement->bindParam(':username', $username);
                    $statement->bindParam(':password', $password);

                    $username = $obj["username"];
                    $password = $obj["password"];

                    $statement->execute();

                    $count = $statement->rowCount();
                    if($count > 0)  
                    {  
                            //echo "success"; 
                            echo $username."-".$password; 
                            return json_encode($statement);
                            //header("location:login_success.php");  
                    }  
                    else  
                    {  
                            $message = '<label>Wrong Data</label>';  
                            echo "failure";
                            return;
                    }  
            }
        }  
        catch(PDOException $error)  
        {  
        $message = $error->getMessage();  
        }
    ?>

Despite the PHP page running successfully, I get the 'Http failure during parsing. I have tried the solution as mentioned here:

Angular 8 error: Http failure during parsing for http

but the issue still persist.

Edit: Here is the response I am receiving:

    error: {
        error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
        text: "admin-admin"
        <prototype>: Object { … }
    }

    headers: {
        lazyInit: function lazyInit()​
        lazyUpdate: null
        normalizedNames: Map(0)
    ​​    <prototype>: Object { … }
    }
    ​
    message: "Http failure during parsing for http://localhost/calibration/login.php"
    name: "HttpErrorResponse"
    ok: false
    status: 200
    statusText: "OK"
    url: "http://localhost/calibration/login.php"
    login.component.ts:37:16
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
dhesikanC
  • 1
  • 7
  • What format does your php API return data in? – Nicholas K Nov 19 '20 at 13:01
  • @NicholasK how can I check the format? Seems to be string. Or are you talking about setting the format using headers() function? – dhesikanC Nov 19 '20 at 13:09
  • Paste the response of your api in the question from the backend. By format I mean, is the response returned as json, xml, string, etc. – Nicholas K Nov 19 '20 at 13:10
  • @NicholasK I have pasted the response. – dhesikanC Nov 19 '20 at 13:16
  • No, thats not what I meant. From a rest client like POSTMAN, etc what is the response you receive when you hit the API directly from there - not through angular. – Nicholas K Nov 19 '20 at 13:17
  • Also, from the error message it looks like your API is returning the response in json format. – Nicholas K Nov 19 '20 at 13:19
  • I do not understand your question. I haven't uploaded the API anywhere in the interne like Postman. I am using a local XAMPP server where I have stored my PHP file. How do I get the response. Sorry, I am new to all this. – dhesikanC Nov 19 '20 at 13:21
  • How do you test your API on local? Don't you use a rest client to verify the response received from the API - I'm asking for that response. FYI, POSTMAN can be run on your local as well. – Nicholas K Nov 19 '20 at 13:23
  • I am new to this, sorry. I just upload that PHP script in a locally working XAMPP Apache server, then upload the angular build file to that server and run it. Can you point me towards an example to what you are talking about. I have no REST api client, I think. – dhesikanC Nov 19 '20 at 13:28
  • On the other hand, you were right about the output. I have now set the response into 'text/plain' and it works. – dhesikanC Nov 19 '20 at 13:32

1 Answers1

0

So I solved this issue by adding

    header('Content-Type: text/plain');

at the top of the PHP script.

dhesikanC
  • 1
  • 7