douchen1924 2014-08-20 09:28
浏览 109
已采纳

跨源请求被阻止:

I have a mobile app that uses an API to authenticate a user via a login form.

This has been working fine up-to today.. and now today when I attempt to login I get the following message in the console log:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://myapp.local/myAppApi/V1/appLogin. 
This can be fixed by moving the resource to the same domain or enabling CORS.

Obviously I need to enable CORS from reading the message, within my myApiController.php I have the following code within my Yii application that I believe should be doing this:

protected function _renderJSON($status = 200)
{
    $statusCodeMessage = $this->_getStatusCodeMessage($status);
    header("HTTP/1.1 {$status} {$statusCodeMessage}");

    // allow for Cross Origin Resource Sharing
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
    header("Access-Control-Allow-Headers: Authorization");
    header('Content-type: application/json');
    echo CJSON::encode($this->jsonArray);

    foreach (Yii::app()->log->routes as $route) {
        if ($route instanceof CWebLogRoute) {
            $route->enabled = false; // disable any weblogroutes
        }
    }
    Yii::app()->end();
}

Could anyone assist on how I can fix this? The app is made with the cordova framework and the API it connects to works via an PHP app built using Yii.

Any advice would be appreciated

-- UPDATE -- I have added the following to my htaccess to no joy however

<ifModule mod_headers.c>
 Header set Access-Control-Allow-Origin: *
 Header set Access-Control-Allow-Headers: Authorization
 Header set Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
</ifModule>

-- UPDATE -- I've come across this link which looks useful https://gist.github.com/sourcec0de/4237402

  • 写回答

1条回答 默认 最新

  • dongyan1548 2014-12-03 06:12
    关注

    Try adding below code in API controller constructor, it works for me.

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, GET, POST");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元