-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
10
  • What format does your php API return data in? Commented Nov 19, 2020 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? Commented Nov 19, 2020 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. Commented Nov 19, 2020 at 13:10
  • @NicholasK I have pasted the response. Commented Nov 19, 2020 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. Commented Nov 19, 2020 at 13:17

1 Answer 1

0

So I solved this issue by adding

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

at the top of the PHP script.

Sign up to request clarification or add additional context in comments.

Comments

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.