React中获取JSON文件:已配置.htaccess的CORS,但第二个文件无法访问
问题:同一目录下单个JSON文件CORS请求失败
我用React代码请求两个同目录的JSON文件,data.json能正常获取,但history-price-gold18.json始终失败,已经在.htaccess添加了CORS配置。
错误信息
Access to fetch at 'https://takhminzan.com/fetch/history-price-gold18.json' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
React代码(index.jsx)
const [price, setPrice] = useState(gold18Price); const jsonFileURL = "https://takhminzan.com/fetch/data.json"; const jsonFileHistoryPriceURL = "https://takhminzan.com/fetch/history-price-gold18.json"; const [historyData, setHistoryData] = useState([]); useEffect(() => { document.title = UITexts.Gold18; fetch(jsonFileURL) .then((response) => response.json()) .then((data) => { localStorage.setItem("price", data.gold_18.close); setPrice(localStorage.getItem("price")); }); fetch(jsonFileHistoryPriceURL) .then((response) => response.json()) .then((data) => { localStorage.setItem("historyData", data.result.close); setHistoryData(localStorage.getItem("historyData")); }); }, []);
尝试过的.htaccess配置
第一种:
<IfModule mod_headers.c> SetEnvIf Origin "https://app.takhminzan.com/*|http://localhost(:[0-9]+)?$" AccessControlAllowOrigin Header set Access-Control-Allow-Origin "*" env=AccessControlAllowOrigin Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept" Header set Access-Control-Allow-Methods "GET, POST, OPTIONS" </IfModule>
第二种(直接允许所有源):
<IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept" Header set Access-Control-Allow-Methods "GET, POST, OPTIONS" </IfModule>
可能的原因及解决思路
- 文件名/路径大小写问题:如果服务器是Linux系统,文件名区分大小写。检查服务器上的实际文件名是否和请求的
history-price-gold18.json完全一致,比如有没有大写字母或者拼写错误。 - 服务器配置的文件规则限制:检查Apache是否有针对特定文件名的额外配置(比如
<Files>指令),可能覆盖了.htaccess的CORS头设置。确保.htaccess文件放在fetch目录下,规则能作用到该目录下的所有文件。 - 缓存导致配置未生效:浏览器或CDN可能缓存了旧的响应头。尝试用
Ctrl+Shift+R强制刷新浏览器,若使用CDN则清除对应文件的缓存。 - 文件权限问题:检查服务器上
history-price-gold18.json的文件权限,确保Apache进程有读取权限(通常设置为644)。权限错误会导致服务器返回403,CORS头无法正常添加。 - mod_headers模块未启用:虽然.htaccess里用了
<IfModule mod_headers.c>,但服务器可能未启用该模块。Linux系统可通过a2enmod headers启用后重启Apache;Windows系统需在httpd.conf里取消注释LoadModule headers_module modules/mod_headers.so。 - 预检请求处理问题:复杂请求会先发送OPTIONS预检请求,检查服务器是否正确处理。可在.htaccess添加以下规则:
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L] </IfModule>
内容的提问来源于stack exchange,提问作者sendous
相关产品推荐
相关产品推荐

