在 React 应用中部署后我无法获取数据
2022-01-16
836
该应用程序在本地运行良好。使用 Firebase 托管部署后出现错误。以下代码是我从 api 资源获取数据的组件
import React, { useEffect, useState } from 'react'
import{ useSelector, useDispatch} from "react-redux"
import { setProducts } from "../containers/redux/actions/productActions"
import ProductComponent from './ProductComponent';
import axios from 'axios';
function ProductList() {
const products = useSelector((state) => state);
const dispatch = useDispatch()
const [searchValue, setSearchValue] = useState('');
const fetchProducts = async ( searchValue) => {
const response = await axios
.get(`http://www.omdbapi.com/?s=${searchValue}&apikey=??????`)
.catch((err) => {
console.log("Err", err);
});
if(response.data.Search){
dispatch(setProducts(response.data.Search));
}
};
useEffect(() => {
fetchProducts(searchValue);
// eslint-disable-next-line react-hooks/exhaustive-deps
},[searchValue]);
console.log("Products: " , products)
return (
<div className='home'>
<div className='search-box'>
<input
value={searchValue} onChange={(e) => setSearchValue(e.target.value)}
type="text"
placeholder="Search.."
>
</input>
</div>
<div className='products-list'>
<ProductComponent />
</div>
</div>
)
}
export default ProductList
已部署应用程序的控制台上出现错误消息:
ProductList.js:21 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
2个回答
if(response.data.Search){ dispatch(setProducts(response.data.Search)); }
首先尝试检查您的响应。
我认为您可能必须在此处证明捕获错误。如果
response.data.Search
未定义,请添加
else
语句或使用
response?.data.Search
Mike
2022-01-16
大多数浏览器会阻止来自安全网站 (https) 的不安全请求 (http)。
将
http://www.omdbapi.com/
更改为
https://www.omdbapi.com/
abraham
2022-01-16