MAMP Pro / APACHE / PHP 未返回 OK 对于 Fetch OPTIONS 预检请求



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


我试过 .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.

能够在@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>

要修复访问控制允许来源中的多个响应,我取消设置访问控制允许原点并在.htaccess中重置它

现在我得到了我期望的 JSON 响应,并在 api 目录上设置了一个基本的 .htpasswd。

最新更新