reactjs - 在 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
解决方案
要定义外部请求,您需要定义协议,否则它将与您的域相关。
在请求的开头添加 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);
});
推荐阅读
- rundeck - 在使用 rundeck-cli 之前是否需要安装 rundeck 软件
- php - 为什么我的 Docker 应用程序不会显示在我的本地服务器上?
- swiftui - swiftUI 中的 App Store 集合视图布局
- google-cloud-iot - 如何在谷歌云物联网中使用根 CA 证书
- javascript - Javascript 读取外部 ICS 文件
- html - CSS设计有助于将内容放在水平线上
- kendo-ui - 如何在 jquery 的 kendo treeview / ui 中只允许选择一个复选框?
- xcode - Xcode 的预处理器宏中的 $(inherited)
- python - 当我期待 TextInput 实例时,Kivy ObjectProperty 为 None,我错过了什么?
- django - 将 Mask-RCNN 与 Flask 和 TF 2.5.0 rc3 一起使用