首页 > 解决方案 > 在 React Uncaught 中获取(承诺中)

问题描述

我在 React 中获取此错误:

未处理的拒绝 (SyntaxError):意外的令牌 < 在 JSON 中的位置 0

我已经发现问题是 fetch 正在将http://localhost:3000/添加到 url 请求的开头,我不知道为什么。

这是我的收获:

export function getRecipes(ingredients, dish) {
    const url = `www.recipepuppy.com/api/?i=${ingredients}&q=${dish}`;
    console.log(url)
        return dispatch => {
            //dispatch(setRecipesRequest());
            fetch(url, {
                method: 'GET'
            }).then(response => response.json())
              .then(json => {
                  console.log('recipes', json);
                  setRecipes(json);
                });
        }

}

即使我已经指定了 url,这是“网络”选项卡在 google chrome 上显示的请求 URL:

http://localhost:3000/www.recipepuppy.com/api/?i=asdasd&q=asdasd

我需要它是:

www.recipepuppy.com/api/?i=asdasd&q=asdasd

标签: reactjsfetch

解决方案


要定义外部请求,您需要定义协议,否则它将与您的域相关。

在请求的开头添加 http/s 应该可以解决您的问题

const url = http://www.recipepuppy.com/api/?i=${ingredients}&q=${dish};

来自 MDN 的示例: https ://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

推荐阅读