我有一个移动应用程序,它使用 API 通过登录表单对用户进行身份验证。
这一直运行良好,直到今天......现在,当我尝试登录时,我在控制台日志中收到以下消息:
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.
显然我需要启用 CORS 来读取消息,在我的 myApiController.php 中我的 Yii 应用程序中有以下代码,我认为应该这样做:
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();
}
任何人都可以帮助我解决这个问题吗?该应用程序是使用 cordova 框架制作的,它连接到的 API 通过使用 Yii 构建的 PHP 应用程序运行。
如有任何建议,我们将不胜感激
-- 更新-- 我已将以下内容添加到我的 htaccess 中,但并不高兴
<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>
-- 更新-- 我遇到了这个看起来很有用的链接 https://gist.github.com/sourcec0de/4237402
最佳答案
尝试在 API Controller 构造函数中添加以下代码,它对我有用。
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");
关于php - 跨源请求被阻止 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25401237/