CORS仅适用于一个请求

时间:2018-02-23 09:37:08

标签: php angularjs cors slim

我正在制作API,到目前为止登录POST请求工作正常

$http({
  url:'http://myurl/public/login',
  method:"POST",
  data:{usuario:$scope.usuario, password:$scope.password}
})
.then(function(response){
  //exito.

  if (response.data.status=="ok"||response.data.status==ok||response.data.status=='ok'){
    $cookies.put('jwtToken', response.data.token);
    $cookies.put('cliente_id', response.data.cliente_id);
    myNavigator.pushPage('components/inicio/inicio.html');
  }

})
.then(function(response){
  //fallo
  if (response.data.status=="error"||response.data.status==error||response.data.status=='error'){
  ons.notification.alert("Usuario y/o contraseña incorrecta");
}

我对登录没有问题,但是当我尝试执行GET请求时

 var cliente_id = $cookies.get('cliente_id');
$http({
 method:"GET",
 url:"http://myurl/public/informacion/"+cliente_id,
 headers:{'Authorization':'Bearer'+' '+ $cookies.get('jwtToken')}
 })
 .then(function(response){
 console.log(response.data);
 })
 .then(function(response){
  console.log("fallo");
  })

我收到此错误

Failed to load http://myurl/public/informacion/1376: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 500.

我的服务器上有这个

$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization, token')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  });

我在某处看到Authorization标题我需要OPTIONS并且我确实拥有它,所以如果有人知道为什么会发生这种情况,请帮忙。

1 个答案:

答案 0 :(得分:-1)

我的PHP应用程序也面临同样的问题,所以我在文件顶部的index.php文件中添加了以下代码

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE, PUT');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true');

希望这会有所帮助。 感谢