apache - 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.
解决方案
在@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 响应。
推荐阅读
- c++ - 程序在一段时间后结束并忽略之后发生的事情
- css - 为什么我的溢出属性不起作用并且任何屏幕小于 1920 像素的东西看起来都很难看?
- reactjs - 为什么 React URL 与 Django Rest 冲突
- android - MissingPluginException(在通道 plugins.flutter.io/firebase_core 上找不到方法 Firebase#initializeCore 的实现)
- html - 最大的框后无法调整大小
- d3.js - D3冰柱图静态节点高度
- node.js - 在 Node.js 项目中包含 Quill 的问题
- python - 如何计算字典中单词的长度
- javascript - firestore 设置/添加功能不起作用,promise 永远不会解决
- python - 为多列绘制多个条形图