【发布时间】:2019-03-15 15:41:29
【问题描述】:
更新:查看答案以获得解决方案。
我已经在 .htaccess 中尝试过
Header always set Access-Control-Allow-Origin "http://localhost:3000"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, PUT, DELETE"
Header always set Access-Control-Allow-Headers "Origin,Content-Type,Accept,Authorization,X-Requested-With"
# Header always set Access-Control-Allow-Credentials true
AuthType Basic
AuthName "API Service"
AuthUserFile /Users/user/Documents/path/path/path/.htpasswd
Require valid-user
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
如何为 MAMP Pro Apache 解决这个问题?
更新:
包装基本身份验证块似乎可以解决 OPTIONS 身份验证预检错误,但现在得到:
Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:3000', but only one is allowed. Origin 'http://localhost:3000' is therefore not allowed access. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
【问题讨论】:
-
要使用 curl 进行测试,您需要让 curl 发送一个 OPTIONS 请求(就像浏览器在尝试 GET 之前所做的那样),如下所示:
curl -i -X OPTIONS --user user:password http://api.site.com/ -
OPTIONS 请求响应的 HTTP 状态码是什么?问题中显示的 curl 调用的响应正文有 服务器遇到内部错误或配置错误,无法完成您的请求 - 尽管正文中有
<title>200 OK</title>,但这表明HTTP 响应状态码不是 200,而是一些 5xx 或 4xx 状态码。如果浏览器没有看到对 OPTIONS 请求的 2xx 响应,则预检失败。 -
@sideshowbarker - 这不是重复的 - 它与帖子类似,但涉及 MAMP 并且 Apache 的所有标头都已正确设置。这不是重复的。
-
Apache 的响应方式与问题中显示的配置告诉它响应的方式完全相同。 “要求有效用户”行告诉 Apache 要求对所有请求进行身份验证——包括 OPTIONS 请求。请参阅 stackoverflow.com/a/31753542/441757 stackoverflow.com/a/19154721/441757 和 stackoverflow.com/a/45623550/441757 等并尝试将“需要有效用户”行(甚至从“AuthType Basic”到“需要有效用户”的 4 行)包装在
<LimitExcept OPTIONS>…</LimitExcept>中。跨度> -
@sideshowbarker - 谢谢 - 好建议,我对 .htaccess 有了更多了解 - 我已将基本身份验证代码块包装在
中,现在收到此错误:对预检的响应请求未通过访问控制检查:“Access-Control-Allow-Origin”标头包含多个值“*,localhost:3000”,但只允许一个。我已经在寻找解决方案,但还没有找到可行的解决方案。另外,.htaccess 文件中只设置了 1 个值,即localhost:3000
标签: apache cors mamp fetch-api preflight