首页 > 解决方案 > MAMP Pro / APACHE / PHP 没有为 Fetch OPTIONS 预检请求返回 OK

问题描述

更新:请参阅答案以获取解决方案。


我在 .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.

标签: apachecorsmampfetch-apipreflight

解决方案


在@sideshowbarker 的帮助下,能够解决这个问题。

JS 获取看起来像这样:

fetch(endpoint, {
  headers: new Headers({
     'Authorization': 'Basic ' + Buffer.from('user:pass').toString('base64'),
     'Content-Type': 'application/json; charset=utf-8'
  }),
  mode: 'cors',
  method: 'GET',
  redirect: 'follow'
})
.then(res => res.json())
.then(json => console.log(json))

.htaccess 看起来像这样

<IfModule mod_headers.c>
Header unset Access-Control-Allow-Origin
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
</IfModule>

<LimitExcept OPTIONS>
AuthType Basic
AuthName "API Service"
AuthUserFile /Users/adamlabarge/Documents/www/headless/tail/.htpasswd
Require valid-user
</LimitExcept>

要修复 Access-Control-Allow-Origin 中的多个响应,我取消设置 Access-Control-Allow-Origin 并将其重置为 .htaccess

现在,我通过在 api 目录上设置的基本 .htpasswd 获得了我期望的 JSON 响应。


推荐阅读