我已经使用SLIM PHP框架创建了一个基本的RESTful服务,现在我正尝试将其连接起来,以便可以从Angular.js项目访问该服务。我已经了解到Angular开箱即用地支持CORS,而我要做的就是Header set Access-Control-Allow-Origin "*"在我的.htaccess文件中添加以下行:
Header set Access-Control-Allow-Origin "*"
我已经做到了,我的REST应用程序仍然可以正常工作(.htaccess错误导致500个内部服务器没有错误),但是当我尝试从test- cors.org测试它时,它抛出了错误。
Fired XHR event: loadstart Fired XHR event: readystatechange Fired XHR event: error XHR status: 0 XHR status text: Fired XHR event: loadend
我的.htaccess文件如下所示
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ /index.php [QSA,L] Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
我还需要添加其他东西到.htaccess中才能使其正常工作,还是有另一种方法可以在服务器上启用CORS?
因为无论如何我都将所有内容转发到index.php,所以我想我会尝试在PHP中设置标头,而不是.htaccess文件,并且它起作用了!好极了!这是我添加到index.php中的其他有此问题的人的内容。
// Allow from any origin if (isset($_SERVER['HTTP_ORIGIN'])) { // should do a check here to match $_SERVER['HTTP_ORIGIN'] to a // whitelist of safe domains header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day } // Access-Control headers are received during OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); }
因为我使用的是Slim,所以我添加了此路由,以便OPTIONS请求获得HTTP 200响应
// return HTTP 200 for HTTP OPTIONS requests $app->map('/:x+', function($x) { http_response_code(200); })->via('OPTIONS');