2017-02-22 46 views
1

Cors在这个API用户/登录问题在postjob /商店API我解决了这个问题添加Cors真正的角度。 之后几天,我把这个API再次相同的错误发生Cors不适用于laravel5.2

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

routes.php文件

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

Route::post('users/login', array('middleware' => 'Cors', 'uses' =>  'Auth\[email protected]')); 
});` 

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

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

}); 

}); 

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

:https://gist.github.com/ZiTAL/3a96710679bd1c21bb381397925c85c0 – ZiTAL

+0

我我在Windows中使用wamp服务器 – UNknow

回答

0

而不是增加头使用foreach

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

给这个一去代替:如果您使用Apache检查这个

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