我是一个新的React本地和我试图编码一个搜索栏与API调用。每次我运行的代码,我得到一个获取数据错误。有人能帮助我吗?
下面是我的代码:
当运行代码时,它给了我以下错误:
错误获取数据:AxiosError:错误失败,状态代码404.有人可以帮助我吗?谢谢!
import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Text, ScrollView, TextInput } from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import axios from 'axios';
function Menu(props) {
const [searchText, setSearchText] = useState('');
const [searchResults, setSearchResults] = useState([]);
const rapidApiKey = "****************p1dfd12jsnf2823d3248e8"; // Replace with your actual RapidAPI key
const handleSearch = async () => {
try {
const response = await axios.get('https://worldwide-restaurants.p.rapidapi.com/search', {
headers: {
'X-RapidAPI-Host': 'worldwide-restaurants.p.rapidapi.com',
'X-RapidAPI-Key': rapidApiKey,
},
params: {
q: searchText,
},
});
setSearchResults(response.data.results);
} catch (error) {
console.error('Error fetching data:', error);
console.log('Error response:', error.response); // Log the detailed error response
}
};
useEffect(() => {
handleSearch(); // Fetch initial data when the component mounts
}, []);
return (
<ScrollView vertical showsVerticalScrollIndicator={false}>
<View style={styles.container}>
<View style={styles.search}>
<TextInput
placeholder='Search'
placeholderTextColor="#fff"
clearButtonMode='always'
autoCapitalize='none'
autoCorrect={false}
style={styles.searchBar}
value={searchText}
onChangeText={(text) => setSearchText(text)}
onSubmitEditing={handleSearch}
/>
<Ionicons name='search' size={25} color={'#8E43ED'} />
</View>
<View style={styles.suggestion}>
{searchResults.map((result) => (
<View key={result.id} style={styles.suggestionBox}>
<Text style={{ color: '#fff' }}>{result.name}</Text>
{/* Add other relevant data fields */}
</View>
))}
</View>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#333',
padding: 10,
paddingTop: 50,
},
search: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 20, // Added margin to separate the search bar from suggestions
},
searchBar: {
paddingHorizontal: 10,
paddingVertical: 5,
borderBottomColor: '#8E43ED',
borderBottomWidth: 2,
color: '#fff',
width: '80%', // Adjusted width for better alignment
},
suggestion: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'center',
justifyContent: 'center',
padding: 10,
gap: 50,
},
suggestionBox: {
backgroundColor: '#8E43ED',
width: 150,
height: 200,
margin: 10,
padding: 10,
borderRadius: 8,
},
});
export default Menu;
字符串
1条答案
按热度按时间weylhg0b1#
HTTP状态代码404代表未找到方法。这意味着没有与提供的方法签名对应的API端点。
就您而言
字符串
您试图访问的搜索端点与您传递的方法主体不一致。请检查后续HTTP端点(搜索其方法签名的端点)并正确指定参数和URL。
Read more about 404 HTTP状态码here