0
votes

I have the following PHP class:

<?php

//header('Access-Control-Allow-Headers: *');
//header('Content-Type: application/json');
//header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');

error_reporting(E_ALL);

class api {
    private $username ="root";
    private $password ="...";
    private $db="...";
    private $host = "localhost";

    public $conn;

    //Connection

    public function connection(){
        try{
            $this->conn = new PDO("mysql:host=$this->host;dbname=$this->db", $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->conn->exec("SET CHARACTER SET utf8");

            return $this->conn;
        }
        catch(PDOException $e){
            return $e->getMessage();
        }

    }

    //Login

    public function login($conn, $user){
        $login = "SELECT username FROM login WHERE username=:user LIMIT 1";
        $execLogin = $this->conn->prepare($login);
        $execLogin->bindValue(":user", $user);
        $execLogin->execute();
        $res = $execLogin->rowCount();

        return $res;
        // if($res>0)
        // {
        //     return json_encode($res);
        // }
        // else{
        //     echo 0;
        // }
    }

}

?>

In this class, I have 2 main functions, the first to connect to the server, and the other is for logging in.

Then, in an Angular web app, if a user added his credentials, they will be sent to the login.php script through HttpClient of Angular 6:

<?php
//header('Access-Control-Allow-Headers: *');
header('Content-Type: application/json');

require_once('../api.php');

//Getting username and password from Angular

$user="brital";
//$pass = json_decode($_POST['credentials']);

$newApi = new api();
$conn = $newApi->connection();
$res = $newApi->login($conn, $user);
echo json_encode($res);
?>

As for the angular script, I created an angular service as an API file to manage all methods related to server connection.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})

export class AuthApiService {
  public credentials:any=[];
  constructor(private http: HttpClient) { }


  login(username, password)
  {
    let headerOptions = new HttpHeaders();
    headerOptions.append('Access-Control-Allow-Origin', '*');
    headerOptions.append('Content-Type', 'application/json');

    let test = {"user": username, "pass": password};
    this.credentials = JSON.stringify(test),
    console.log("hi "+ this.credentials);
    return this.http.post('http://dev.local/scripts/login.php', this.credentials, {
      headers: headerOptions
    }).pipe(map(
        res=>{

          console.log(res)
        },
        err=>
          console.log(err)
      ))
  }
}

And here is the button html:

<a id="btn-login"  (click)="login()" class="btn btn-success">Login </a>

As you see I am sending a and b as testing values for the functions.

I had the following error:

Http failure during parsing for http://dev.local/scripts/login.php

error : SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:28274:51) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2743:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:56150:33) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2742:36) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2510:47) at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:2818:34) at invokeTask (http://localhost:4200/polyfills.js:3862:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:3888:17) message : "Unexpected token < in JSON at position 0"

And here is a screenshot:

enter image description here

From the network tab, I had an error returned from login.php:

Notice: Undefined index: credentials in C:\wamp64\www\dev\scripts\login.php on line 8

And if you check my login.php, I already commented this line, so I don't know why is giving me such an error.

2
what is showing respond in Network ? - ahkeno
error at line 8 of login.php credentials is undefined, but this line is commented. So why it's reading it. - alim1990
Try to put res.json(); in map after console.log . - hrdkisback
Tried it and get a new error error TS2339: Property 'json' does not exist on type 'HttpResponse<Object>' - alim1990

2 Answers

1
votes

Okay I found the solution:

it seems that I should add the following headers:

headerOptions.append('Access-Control-Allow-Origin', '*');
headerOptions.append('Access-Control-Request-Headers', '*');
headerOptions.append('Content-Type', 'application/json');
headerOptions.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');

And from the Apache, we should go to Apache services and check headers_modules.

Then, we should change the httpd.conf, and the following:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin: *
</IfModule>
1
votes

Same error was coming when I was trying to send one string message (Like : res.send( "Message from node" )) from node to angular.

I just changed the string into JSON format like {"msg" : "Message from node"}, I was getting the data after this.

I tried after adding this res.setHeader('Content-Type', 'text/plain') it was returning same error in the beginning.