0

I am working on an application with Angular2 in front end, accessing a PHP Restfull API for the backend and I can't figure out why a simple login request made via POST is not being "translated" by the server side.

The Angular2 service (API_PATH and SOME_CODE_HERE are just to avoid expose my real code)

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { Router} from "@angular/router";

@Injectable()
export class AuthService {

constructor(private http: Http, private router: Router) {
    SOME_CODE_HERE
}

signIn(email: string, password: string): Observable<boolean> {
    return this
        .http
        .post('API_PATH/auth', JSON.stringify({ email: email, password: password }))
        .map( SOME_CODE_HERE )
        .catch(
            (error: Response) => { 
                console.log(error);
                return Observable.throw(error);
            }
        );
}

}

The .htaccess. I am very inclined to believe that the problem is here, with the .htaccess.

<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On

RewriteBase <API_PATH>

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ router.php?request=$1 [QSA,L]
</IfModule>

The router.php

<?php
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
    $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}

try {

    /*$_REQUEST['request'] brings exactly what I want from .htacces, 
    that is the endpoint name. But how could access the arguments
    (email and password) sent via Angular2 Post?*/

    require_once $_REQUEST['request'] . ".php";
    $API = new $_REQUEST['request']($_REQUEST, $_SERVER['HTTP_ORIGIN']);
    echo $API->processAPI();
} catch (Exception $e) {
    echo json_encode(Array('error' => $e->getMessage()));
}

The API.php

<?php
abstract class API
{
protected $method = '';
protected $endpoint = '';
protected $args = Array();
protected $file = Null;

public function __construct($request) {

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: *");
    header("Content-Type: application/json");

    $this->args = $request;
    $this->endpoint = array_shift($this->args);
    $this->method = $_SERVER['REQUEST_METHOD'];

    if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
        if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
            $this->method = 'DELETE';
        } else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
            $this->method = 'PUT';
        } else {
            throw new Exception("Unexpected Header");
        }
    }

    switch($this->method) {
        case 'DELETE':
        case 'POST':
            $this->request = $this->_cleanInputs($_POST);
            break;
        case 'GET':
            $this->request = $this->_cleanInputs($_GET);
            break;
        case 'PUT':
            $this->request = $this->_cleanInputs($_GET);
            $this->file = file_get_contents("php://input");
            break;
        default:
            $this->_response('Invalid Method', 405);
            break;
    }
}

public function processAPI() {
    if (method_exists($this, $this->endpoint)) {
        return $this->_response($this->{$this->endpoint}($this->args));
    }
    return $this->_response("No Endpoint: $this->endpoint", 404);
}

private function _response($data, $status = 200) {
    header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
    return json_encode($data);
}

private function _cleanInputs($data) {
    $clean_input = Array();
    if (is_array($data)) {
        foreach ($data as $k => $v) {
            $clean_input[$k] = $this->_cleanInputs($v);
        }
    } else {
        $clean_input = trim(strip_tags($data));
    }
    return $clean_input;
}

private function _requestStatus($code) {
    $status = array(  
        200 => 'OK',
        404 => 'Not Found',   
        405 => 'Method Not Allowed',
        500 => 'Internal Server Error',
    ); 
    return ($status[$code])?$status[$code]:$status[500]; 
}
}

And finally the auth.php

<?php
require_once 'API.php';

class auth extends API
{

    public function __construct($request, $origin) {
        parent::__construct($request);
    }

    protected function auth($args) {
    //Why I can't find login and password ?
    }
}
Carlos Ost
  • 492
  • 7
  • 22
  • 1
    It will be sent up as json body so it will be in `php://input`, if you need it like a classical POST then your need to add content type header `application/x-www-form-urlencoded` to the ajax call. – Lawrence Cherone Jun 13 '17 at 08:07
  • Possible dupe: https://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data – Lawrence Cherone Jun 13 '17 at 08:07
  • Possible duplicate of [AngularJs $http.post() does not send data](https://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data) – Masud Jahan Jun 13 '17 at 08:47

0 Answers0