繁体   English   中英

Cors不适用于laravel5.2

[英]Cors not apply in laravel5.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;
      });
        }; 

而不是使用foreach添加标头:

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

改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM