Cors不适用于laravel5.2

时间:2017-02-22 06:23:55

标签: php angularjs laravel-5.2

在postjob / store api中工作这个api用户/登录问题的人我解决了这个问题,在角度中添加了cors true。 几天后,我再次称这个api发生同样的错误

  

XMLHttpRequest无法加载http://192.168.10.5/jobpost1/public/api/job。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:9001”访问。

routes.php文件

Route::group(['prefix' => 'api'], function () {

Route::post('users/login', array('middleware' => 'Cors', 'uses' =>      'Auth\AuthController@login')); 
});`

Route::group(['prefix'=>'api'], function()
{

 Route::group(['middleware'=>'jwt-auth'], function ()
  {
    Route::post('postjob/store', array('middleware' => 'Cors', 'uses'=>   'PostController@store'));

 });

});

Cors.php

 class Cors
 {

public function handle($request, Closure $next)
{




    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Origin'=> '*',
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin',
        'Access-Control-Allow-Credentials' => 'true'
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
}

角度代码

                return $http({
                method: 'POST',
                url: 'http://192.168.10.4/jobpost1/public/api/job',
                 cors: true,
                 xhrFields: { 
                 withCredentials: true
                  },
                params: {
      "token" :token,
      "user_id": userId,
      "job_shift": job_shift,
      "job_type": job_type,
      "job_description":job_description,
      "degree_title": degree_title,
      "city": city,
      "experience": experience,
      "career_level": career_level,
      "gender":gender,
     "total_position": total_position,
    "minimum_edu":minimum_edu,
     "apply_before": apply_before
                }
            }).then(function successCallback(response, status) {
      callback(response, status);
      debugger;
    }
      , function errorCallback(response, status) {
        callback(response, status);
        debugger;
      });
        }; 

1 个答案:

答案 0 :(得分:0)

而不是使用foreach添加标题:

foreach($headers as $key => $value)
    $response->header($key, $value);

改为:

$response->headers->add($headers);