PHP Server端无法转换Angular2 Post请求

时间:2017-06-13 07:58:30

标签: php .htaccess angular api post

我正在使用前端的Angular2应用程序,访问后端的PHP Restfull API,我无法弄清楚为什么通过POST进行的简单登录请求没有被服务器端“翻译”。 / p>

Angular2服务(API_PATH和SOME_CODE_HERE只是为了避免暴露我的真实代码)

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);
            }
        );
}

}

.htaccess。我非常倾向于认为问题就在这里,使用.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>

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()));
}

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]; 
}
}

最后是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 ?
    }
}

0 个答案:

没有答案