So I have bee trying to make a simple login page using Angular 10 as frontend and PHP as a server-side backend language(no PHP frameworks used here).
Here is my login.service.ts file:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams} from '@angular/common/http';
//import { User } from '../shared/user.model';
import { throwError } from 'rxjs';
//import { map, tap } from 'rxjs/operators'
export interface LoginResponse{
id:bigint;
username:string;
password:string
user_date:string
show_user:number;
save_time:string
}
@Injectable({
providedIn:'root'
})
export class LoginService{
constructor(private http: HttpClient){}
loginUser(username: string, password:string){
const user = JSON.stringify( { "user" : {"username":username, "password" : password} });
return this.http.post<any>(
"http://localhost/calibration/login.php",
user,
{
headers: new HttpHeaders({'Content-Type':'text/plain'})
}
);
}
handleError(errorResponse:HttpErrorResponse){
console.log(errorResponse);
return throwError("Something Went Wrong");
}
}
and here is my login.php file:
<?php
session_start();
require_once("connection.php");
var_dump($conn);
try
{
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
var_dump($_POST);
if(isset($_POST["user"]))
{
$obj = json_decode($_POST["user"]);
$query = "SELECT * FROM user_master WHERE username = ? AND password = ?";
$statement = $conn->prepare($query);
$statement->bind_param(1, $username, $_POST['username']);
$statement->bind_param(2, $password, $_POST['password']);
$username = $obj->username;
$password = $obj->password;
$statement->execute();
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
//header("location:login_success.php");
}
else
{
$message = '<label>Wrong Data</label>';
}
}
}
catch(PDOException $error)
{
$message = $error->getMessage();
}
?>
Here is the response I received after trying to run the PHP file through the login.service.ts:
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null
},
"status": 200,
"statusText": "OK",
"url": "http://localhost/calibration/login.php",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure during parsing for http://localhost/calibration/login.php",
"error": {
"error": {},
"text": "object(PDO)#1 (0) {\n}\narray(0) {\n}\n "
}
}
text: "object(PDO)#1 (0) {\n}\narray(0) {\n}\n
Any help?
Update: Made some changes to the code to reflect some of the recommendations given below