axios 我无法在react应用程序中部署后获取数据

jdgnovmf  于 2022-11-05  发布在  iOS
关注(0)|答案(2)|浏览(204)

这个应用程序在本地运行得很好。在我使用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

已部署应用程序的控制台上显示错误消息:
js:21未捕获(在承诺中)类型错误:无法读取未定义的属性(阅读'data')

8zzbczxx

8zzbczxx1#

if(response.data.Search){
       dispatch(setProducts(response.data.Search));
   }

请先检查您的响应。我认为您可能需要在此处证明catch error。如果response.data.Search未定义,请添加else语句,或者使用response?.data.Search

rseugnpd

rseugnpd2#

大多数浏览器将阻止来自安全站点(https)的不安全请求(http)。
http://www.omdbapi.com/更改为https://www.omdbapi.com/

相关问题