You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native调用Yelp API遇fetch错误:Invalid name求助

解决React Native调用Yelp API时的TypeError: Invalid name错误

错误原因分析

你的代码存在几个关键问题引发了该错误:

  • 请求头键名包含无效空格:'x- requested - wth'是非法的HTTP头名称,HTTP头键名不允许有空格,正确写法应为'X-Requested-With'
  • 错误设置响应头:Access-Control-Allow-Origin是服务器端返回的响应头,前端发起请求时无需设置该字段
  • 冗余函数参数:getRestaurantsFromYelp中的req, res是Node.js后端接口的参数,React Native前端代码完全不需要这些参数

修正后的代码

const getRestaurantsFromYelp = async () => {
  const yelpUrl = `https://api.yelp.com/v3/businesses/search?term=restaurants&location=NYC`;
  const apiOptions = {
    method: 'GET',
    headers: {
      accept: 'application/json',
      'X-Requested-With': 'XMLHttpRequest',
      Authorization: `Bearer ${YELP_API_KEY}`,
    },
  };
  try {
    const response = await fetch(yelpUrl, apiOptions);
    const json = await response.json();
    setRestaurantData(json.businesses);
  } catch (error) {
    console.error('获取餐厅数据失败:', error);
  }
};

useEffect(() => {
  getRestaurantsFromYelp();
}, []);

额外说明

  • 统一使用async/await语法,避免await与.then()混用,让代码逻辑更清晰
  • 添加try/catch捕获请求过程中的异常,便于调试定位问题
  • React Native的fetchAPI原生支持跨域请求,无需额外配置跨域相关请求头

内容的提问来源于stack exchange,提问作者Savoy D Rath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:06:13