在.htaccess中启用cors [英] enable cors in .htaccess
问题描述
我已经使用SLIM PHP框架创建了一个基本的RESTful服务,现在我试图连接它,以便我可以从Angular.js项目访问服务。我已经阅读,Angular支持CORS开箱,我需要做的是添加以下行:头设置访问控制允许原产地*
到我的。 htaccess文件。
I have created a basic RESTful service with the SLIM PHP framework and now I'm trying to wire it up so that I can access the service from an Angular.js project. I have read that Angular supports CORS out of the box and all I needed to do was add this line: Header set Access-Control-Allow-Origin "*"
to my .htaccess file.
我这样做,我的REST应用程序仍然工作(没有500内部服务器错误从一个坏的.htaccess),但当我尝试从 test-cors.org 它会抛出一个错误。
I've done this and my REST application is still working (no 500 internal server error from a bad .htaccess) but when I try to test it from test-cors.org it is throwing an error.
Fired XHR event: loadstart
Fired XHR event: readystatechange
Fired XHR event: error
XHR status: 0
XHR status text:
Fired XHR event: loadend
我的.htaccess文件看起来像这样
My .htaccess file looks like this
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?
Is there something else I need to add to my .htaccess to get this to work properly or is there another way to enable CORS on my server?
推荐答案
因为我有一切被转发到index.php反正我认为我会尝试设置标头在PHP而不是.htaccess文件,它的工作!好极了!这是我添加到index.php为任何人有这个问题。
Since I had everything being forwarded to index.php anyway I thought I would try setting the headers in PHP instead of the .htaccess file and it worked! YAY! Here's what I added to index.php for anyone else having this problem.
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
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']}");
}
http://stackoverflow.com/questions/8719276/cors-with-php-headers\">这个问题
credit goes to slashingweapon for his answer on this question
因为我使用Slim I添加此路由,以便OPTIONS请求获得HTTP 200响应
Because I'm using Slim I added this route so that OPTIONS requests get a HTTP 200 response
// return HTTP 200 for HTTP OPTIONS requests
$app->map('/:x+', function($x) {
http_response_code(200);
})->via('OPTIONS');
这篇关于在.htaccess中启用cors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!