I am getting such Kind Of Problem : Uncaught (in promise) SyntaxError: Unexpected end of JSON input
I am getting such Kind Of Problem : Uncaught (in promise) SyntaxError: Unexpected end of JSON input
我正在使用 React js 并使用 mongo 数据库。我正在尝试通过获取来获取数据。但我收到这种类型的错误:未捕获(承诺)语法错误:JSON 输入
意外结束
const [product, setProduct] = useState({});
useEffect(() => {
const url = `http://localhost:5000/product/${id}`;
fetch(url)
.then((res) => res.json())
.then((data) => setProduct(data));
}, [id]);
您在 useEffect 中的代码是正确的,您可能收到此错误的原因是
- 后台没有JSON数据
- 可能您收到的JSON不正确JSON
您可以通过将 res.json() 替换为 res.text() 然后 console.log 来确认这一点
您应该在 fetch
的方法调用链中包含一个 .catch()
调用,以便您可以处理来自 API 的错误或格式错误的输入。错误是说它是“未捕获的”,因为没有 catch
子句。
即
fetch(url)
.then((res) => res.json())
.then((data) => setProduct(data))
.catch((error) => console.error("Something went wrong: ", error))
我正在使用 React js 并使用 mongo 数据库。我正在尝试通过获取来获取数据。但我收到这种类型的错误:未捕获(承诺)语法错误:JSON 输入
意外结束const [product, setProduct] = useState({});
useEffect(() => {
const url = `http://localhost:5000/product/${id}`;
fetch(url)
.then((res) => res.json())
.then((data) => setProduct(data));
}, [id]);
您在 useEffect 中的代码是正确的,您可能收到此错误的原因是
- 后台没有JSON数据
- 可能您收到的JSON不正确JSON
您可以通过将 res.json() 替换为 res.text() 然后 console.log 来确认这一点
您应该在 fetch
的方法调用链中包含一个 .catch()
调用,以便您可以处理来自 API 的错误或格式错误的输入。错误是说它是“未捕获的”,因为没有 catch
子句。
即
fetch(url)
.then((res) => res.json())
.then((data) => setProduct(data))
.catch((error) => console.error("Something went wrong: ", error))