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

时间:2018-10-10 16:45:39

标签: apache cors mamp fetch-api preflight

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


我已经尝试过.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解决此问题?

更新:

包装基本auth块似乎可以解决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.

1 个答案:

答案 0 :(得分:0)

可以在@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响应。