已配置X-RapidAPI-Key仍返回「未订阅该API」错误的解决办法
解决"You are not subscribed to this API"错误
问题场景
使用RapidAPI提供的YouTube-v31接口,已将API密钥存入项目根目录.env文件,但调用接口时始终收到错误:
You are not subscribed to this API
[[Prototype]]
Object
相关代码如下:
API封装代码
import axios from "axios"; const BASE_URL = 'https://youtube-v31.p.rapidapi.com'; const options = { params: { maxResults: '50' }, headers: { 'X-RapidAPI-Key': process.env.REACT_APP_RAPID_API_KEY, 'X-RapidAPI-Host': 'youtube-v31.p.rapidapi.com' } }; export const fetchFromAPI = async(url) =>{ const { data } = await axios.get(`${BASE_URL}/${url}`, options); return data; }
数据获取代码
import { fetchFromAPI } from '../utils/fetchFromAPI'; const Feed = () => { const [selectedCategory, setSelectedCategory] = useState('New'); const [videos, setVideos] = useState([]); useEffect (() =>{ fetchFromAPI(`search?part=snippet&q=${selectedCategory}`) .then((data) => setVideos(data.items)) .catch(error => { if (error.response) { console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { console.log(error.request); } else { console.log('Error', error.message); } }); }, [selectedCategory]); // 补充:原代码缺少依赖数组,建议添加避免无限触发请求 }
解决步骤
- 确认接口订阅状态:登录RapidAPI后台,找到该YouTube-v31接口,检查是否完成订阅操作(即使是免费套餐也需要手动点击「Subscribe」按钮确认)。很多时候跟着教程操作会遗漏这一步,导致密钥无法访问接口。
- 验证API密钥正确性:在RapidAPI的「My Apps」页面,查看当前使用的API密钥所属的应用是否已订阅该接口。直接复制后台的密钥替换
.env中的内容,避免复制时出现空格或字符缺失。 - 检查.env配置规范:React项目要求环境变量必须以
REACT_APP_开头,确保你的变量名是REACT_APP_RAPID_API_KEY,且.env文件放在项目根目录,没有文件名拼写错误(比如写成.env.local或.env.prod但未对应环境)。修改.env后必须重启开发服务器,否则新变量不会加载。 - 核对请求头参数:确认代码中的
X-RapidAPI-Host值为youtube-v31.p.rapidapi.com,和接口文档完全一致,不能有拼写错误。 - 直接测试请求:用curl或Postman发送原始请求验证,排除项目配置问题:
curl --request GET \ --url 'https://youtube-v31.p.rapidapi.com/search?part=snippet&q=New&maxResults=50' \ --header 'X-RapidAPI-Key: 你的API密钥' \ --header 'X-RapidAPI-Host: youtube-v31.p.rapidapi.com'
如果该请求仍报错,说明是RapidAPI订阅或密钥问题;如果成功,则排查项目中环境变量的加载逻辑。
内容的提问来源于stack exchange,提问作者okunade femi joel
相关产品推荐
相关产品推荐

