Angular post方法到php

时间:2017-06-22 19:01:57

标签: php angularjs lumen

我一直试图将数据从角度发布到php,但我觉得很困难。 这是角度控制器的方法:

function submit() {      
        var JSONObject = {
             "name":$rootScope.name,
             "surname":$rootScope.surname,
             "email":$rootScope.email,
             "review":$rootScope.review
        };
        debugger;
        var Results = UniversalService.PostReview(JSONObject);
    }

然后转到UniversalService,我的$ http.post方法是:

function PostReview(JSONObject) {
        debugger;
        $http.post('http://localhost:8000/creation', JSONObject).then();
        debugger;
    }

直到这一点,它必须将数据发送到php(我的web api服务是与Lumen框架)

在我的DatabaseController.php中我希望收到我的json对象(我​​是初学者,所以我希望我失败了)

public function created(Request $request)
{
    $inputJSON = file_get_contents('php://input');
    $input= json_decode( $inputJSON, TRUE ); //convert JSON into array

    print_r(json_encode($input));
   /* $user=[
        'name'=>$request->input('name'),
        'surname'=>$request->input('surname'),
        'email'=>$request->input('email'),
        'review'=>$request->input('review'),
    ];
    $time=$this->getTime();*/
 //  return DatabaseModel::newUser($user);

}
在routes.php中

$app->post('/creation', [ 'as'=>'creation','uses'=> 'DatabaseController@created']);

我在这里绝望地使用和发布,我似乎无法正确行事。同样在routes.php中我启用了标题(' Access-Control-Allow-Origin:*');而且我不确定我是否必须在角度方面这样做(以及如何)。

我得到的是一堆错误enter image description here

但是postman似乎工作,我在那里有额外的功能,当我输入:http://localhost:8000/creation给邮递员时,我从另一个我在create()中调用的函数得到json对象和时间的空白

2 个答案:

答案 0 :(得分:1)

我相信你会被Chrome中的OPTIONS飞行前请求抓住。请注意,在控制台中它抱怨您的“OPTIONS”请求而不是POST本身。在没有看到您的服务器代码的情况下,这里有一个如何处理它的示例,以及在飞行前OPTIONS的响应中需要的标题。

// respond to preflights
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  // return only the headers and not the content
  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']){
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: X-Requested-With');
  }
  exit;
}

可以在此处找到更详尽的解释(以及我抓住该片段的位置):https://remysharp.com/2011/04/21/getting-cors-working

答案 1 :(得分:1)

今天与其他三位程序员解决了我的问题。正如@jheimbouch所说,问题在于Angular将OPTIONS方法发送给php服务。提到的另一个问题是科尔。我们的解决方案是 在/bootstrap/app.php中我们添加了:  $app->middleware(['Cors' => App\Http\Middleware\CorsMiddleware::class]);

然后在/ Http / Midleware中添加了文件CorsMiddleware.php,它解决了我所有的问题:

<?php

命名空间App \ Http \ Middleware;

使用Closure; 使用Illuminate \ Http \ Response;

class CorsMiddleware {

protected $settings = [
            'origin' => '*',    // Wide Open!
            'allowMethods' => 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'];

protected function setOrigin($req, $rsp)
{
    $origin = $this->settings['origin'];
    if (is_callable($origin))
    {
        // Call origin callback with request origin
        $origin = call_user_func($origin, $req->header("Origin"));
    }
    $rsp->header('Access-Control-Allow-Origin', $origin);
}

protected function setExposeHeaders($req, $rsp)
{
    if (isset($this->settings->exposeHeaders))
    {
        $exposeHeaders = $this->settings->exposeHeaders;

        if (is_array($exposeHeaders))
        $exposeHeaders = implode(", ", $exposeHeaders);

        $rsp->header('Access-Control-Expose-Headers', $exposeHeaders);
    }
}

protected function setMaxAge($req, $rsp)
{
    if (isset($this->settings['maxAge']))
    $rsp->header('Access-Control-Max-Age', $this->settings['maxAge']);
}

protected function setAllowCredentials($req, $rsp)
{
    if (isset($this->settings['allowCredentials']) && $this->settings['allowCredentials'] === True)
    $rsp->header('Access-Control-Allow-Credentials', 'true');
}

protected function setAllowMethods($req, $rsp)
{
    if (isset($this->settings['allowMethods']))
    {
        $allowMethods = $this->settings['allowMethods'];

        if (is_array($allowMethods))
        $allowMethods = implode(", ", $allowMethods);

        $rsp->header('Access-Control-Allow-Methods', $allowMethods);
    }
}

protected function setAllowHeaders($req, $rsp)
{
    if (isset($this->settings['allowHeaders']))
    {
        $allowHeaders = $this->settings['allowHeaders'];

        if (is_array($allowHeaders))
        $allowHeaders = implode(", ", $allowHeaders);

    }
    else // Otherwise, use request headers
    {
        $allowHeaders = $req->header("Access-Control-Request-Headers");
    }

    if (isset($allowHeaders))
    $rsp->header('Access-Control-Allow-Headers', $allowHeaders);

}

protected function setCorsHeaders($req, $rsp)
{
    // http://www.html5rocks.com/static/images/cors_server_flowchart.png
    // Pre-flight
    if ($req->isMethod('OPTIONS'))
    {
        $this->setOrigin($req, $rsp);
        $this->setMaxAge($req, $rsp);
        $this->setAllowCredentials($req, $rsp);
        $this->setAllowMethods($req, $rsp);
        $this->setAllowHeaders($req, $rsp);
    }
    else
    {
        $this->setOrigin($req, $rsp);
        $this->setExposeHeaders($req, $rsp);
        $this->setAllowCredentials($req, $rsp);
    }
}

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next) {

    if ($request->isMethod('OPTIONS')) {
        $response = new Response("", 200);
    }
    else {
        $response = $next($request);
    }

    $this->setCorsHeaders($request, $response);

    return $response;
}}

希望这会对某人有所帮助,因为我花了很多时间才能完成所有工作!无论如何,非常感谢所有帮助过的人:)