React TypeScript中使用Fetch调用外部API遇CORS问题求助
React TS调用Airtable API的CORS错误解决方法
问题详情
遇到的CORS错误:
Access to fetch at 'https://api.airtable.com/{my_data_base}' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response.
当前使用的React TSX组件代码:
import { FC, useEffect } from 'react'; const Collection: FC = () => { useEffect(() => { fetch('https://api.airtable.com/v0/my_data_base', { headers: { mode: 'no-cors', Authentication: 'Bearer my_token', }, }) .then((resp) => resp.json()) .then((data) => { console.log(data); }); }, []); return <div>Collection Page Component</div>; }; export default Collection
无授权的公开API可正常调用,尝试浏览器CORS扩展无效,需要解决该问题。
核心问题与修复步骤
1. 修正Fetch配置的两处错误
你的代码里有两个致命错误,直接导致了CORS报错和请求失败:
mode属性放错位置:mode是Fetch配置的顶层选项,不属于headers对象- 授权头拼写错误:Airtable要求的授权头是
Authorization(你写的是Authentication,少了字母z)
修正后的代码:
import { FC, useEffect } from 'react'; const Collection: FC = () => { useEffect(() => { // 注意:URL需要补充具体的表名,格式为 /v0/{baseId}/{tableName} fetch('https://api.airtable.com/v0/my_data_base/YourTableName', { method: 'GET', headers: { 'Authorization': 'Bearer my_token', 'Content-Type': 'application/json' } }) .then((resp) => { // 先检查请求是否成功 if (!resp.ok) throw new Error(`请求失败:${resp.status}`); return resp.json(); }) .then((data) => console.log(data)) .catch(err => console.error('请求出错:', err)); }, []); return <div>Collection Page Component</div>; }; export default Collection
2. 开发环境绕过CORS的代理方案
如果修正后仍有CORS问题(Airtable官方API支持CORS,但本地开发偶发限制),可以使用React内置代理:
- 在项目根目录的
package.json中添加代理配置:"proxy": "https://api.airtable.com" - 修改Fetch请求为相对路径:
fetch('/v0/my_data_base/YourTableName', { headers: { 'Authorization': 'Bearer my_token', 'Content-Type': 'application/json' } })
React会自动将请求转发到Airtable API,绕过浏览器的CORS检查。
3. 重要安全提醒
绝对不要在前端代码中暴露你的Airtable Token!任何人都能通过浏览器开发者工具获取到Token,进而操作你的Airtable数据。正确的做法是:
- 搭建自己的后端服务,将Token存储在后端
- 前端调用自己的后端接口,由后端代为请求Airtable API
内容的提问来源于stack exchange,提问作者dariusz
相关产品推荐
相关产品推荐

