由于CORS策略限制,从源 'http://localhost:3000' 访问 XMLHttpRequest 请求 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=INR&order=market_cap_desc&per_page=100&page=1&sparkline=false' 被阻止。请求资源上缺少 'Access-Control-Allow-Origin' 头部。
以下是你的代码:
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { CoinList } from '../config/api';
import { CrytpoState } from '../CryptoContext';
import { Container, LinearProgress, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, ThemeProvider, Typography, createTheme, makeStyles } from '@material-ui/core';
import { useNavigate } from "react-router-dom";
const CoinsTable = () => {
const [coins, setCoins] = useState([]);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState("");
const navigate = useNavigate();
const { currency } = CrytpoState();
const fetchCoins = async () => {
setLoading(true);
try {
const { data } = await axios.get(CoinList(currency), { crossDomain: true });
setCoins(data);
} catch (error) {
console.error("Error fetching coins:", error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchCoins();
}, [currency]);
// 创建深色主题样式
const darkTheme = createTheme({
palette: {
primary: {
main: "#fff",
},
type: "dark",
},
});
// 搜索处理函数
const handleSearch = () => {
return coins.filter(
(coin) =>
coin.name.toLowerCase().includes(search.toLowerCase()) ||
coin.symbol.toLowerCase().includes(search.toLowerCase())
);
};
const useStyles = makeStyles(() => ({
row: {},
}));
const classes = useStyles();
return (
<ThemeProvider theme={darkTheme}>
{/* 页面内容 */}
</ThemeProvider>
);
};
// 由于跨域问题,我无法直接解决,但通常来说,你需要确保API服务器允许来自'http://localhost:3000'的请求。这通常通过在服务器端配置'Access-Control-Allow-Origin'头部来实现。
任何帮助都将不胜感激,因为我目前无法解决这个CORS头部缺失的问题。