【问题标题】:CORS only working for one request [duplicate]CORS 仅适用于一个请求 [重复]
【发布时间】:2018-08-03 08:01:31
【问题描述】:

我正在制作一个 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 并且我确实拥有它,所以如果有人知道为什么会发生这种情况,请帮助。

【问题讨论】:

  • "响应的 HTTP 状态代码为 500。" — 你需要调试你的 500 错误。
  • “我在某处读到,对于带有授权的标头,我需要 OPTIONS,我确实拥有它”——错误消息没有提到预检,因此选项似乎不是问题请求。
  • @jaime 你试过添加 header('Access-Control-Allow-Credentials: true');
  • @BinitGhetiya 等一下我正在尝试,因为我添加了一些代码,现在登录也不起作用哈哈哈
  • 你在使用 chrome 吗?然后尝试安装chrome.google.com/webstore/detail/cors-toggle/…

标签: php angularjs slim


【解决方案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');

希望这会有所帮助。 谢谢

【讨论】:

  • 那无济于事。大致相等的代码已经存在问题中,并且有一个 500 错误需要处理。
  • 没有工作... :l
猜你喜欢
  • 2012-10-08
  • 1970-01-01
  • 2021-07-19
  • 2014-09-05
  • 2020-06-02
  • 2015-03-01
  • 2017-06-20
  • 2018-08-10
  • 2021-03-10
相关资源
最近更新 更多