【问题标题】:handling CORS preflight request in Apache在 Apache 中处理 CORS 预检请求
【发布时间】:2014-10-31 18:46:40
【问题描述】:

我有一个使用 Yeoman 部署的 AngularJS 应用程序。 Cakephp RESTful 后端。

Angular 应用程序发送 OPTIONS 预检请求,后端以禁止 (403) 响应,在 nginx 中我使用了这个来解决这个问题:

if ($request_method = 'OPTIONS') {
     add_header 'Access-Control-Allow-Origin' '*'; 
     add_header 'Access-Control-Allow-Credentials' 'true';
     add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE'; 
     add_header 'Access-Control-Allow-Headers' 'X-AuthTokenHeader,Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';   
     add_header 'Access-Control-Max-Age' 1728000;
     add_header 'Content-Type' 'text/plain charset=UTF-8';
     add_header 'Content-Length' 0;
     return 204; 
}

如何在 Apache 中执行此操作?请提供一些初步的指导/cmets,之后我会弄清楚细节并用细化的细节改进问题。

【问题讨论】:

    标签: apache http-headers


    【解决方案1】:

    将此添加到您的 .htaccess 文件到您的 apache 根目录:

    Header add Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
    

    确保激活 apache 模块头:

    a2enmod headers
    

    来源:https://stackoverflow.com/a/11691776/1494875

    【讨论】:

      【解决方案2】:

      我有同样的问题,给出的答案并没有解决问题。

      通过环顾四周,我发现您可以使用重写来做到这一点,例如:

      RewriteEngine On                  
      RewriteCond %{REQUEST_METHOD} OPTIONS 
      RewriteRule ^(.*)$ $1 [R=200,L]    
      

      (确保启用重写模式)

      那么你应该使用“总是设置”来设置标题,例如:

      Header always set Access-Control-Allow-Origin "*"                   
      Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
      

      此处解释:https://serverfault.com/questions/231766/returning-200-ok-in-apache-on-http-options-requests

      【讨论】:

      • 在糟糕的 2 天后你救了我!
      【解决方案3】:

      如果有帮助 - 我正在使用身份验证,所以我还必须添加以下内容以使 POST 请求为我工作:

      <LimitExcept OPTIONS>
        Require valid-user 
      </LimitExcept>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-15
        • 2019-08-29
        • 2016-02-17
        • 2013-11-25
        • 2012-11-17
        • 2014-05-23
        • 1970-01-01
        • 2014-08-16
        相关资源
        最近更新 更多