Access to XMLHttpRequest at ‘https://api.coingecko.com/api/v3/coins/markets?vs_currency=INR&order=market_cap_desc&per_page=100&page=1&sparkline=false’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
this is my code:
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 history=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);
}
};
console.log(coins);
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}>
<Container style={{
textAlign:"center"
}}>
<Typography
variant="h4"
style={{
margin:18,
fontFamily:"Montserrat",
}}>
CryptoCurrency Prices by Market Cap!
</Typography>
<TextField label="Search For a Crpto Currency..!" variant="outlined"
style={{
marginBottom:20,
width:"100%"
}}
onChange={(e)=>setSearch(e.target.value)}
/>
<TableContainer>
{loading?(
<LinearProgress style={{backgroundColor:"gold"}} />
) :(
<Table>
<TableHead style={{backgroundColor:"#EEBC1D"}}>
<TableRow>
{["Coin","Price","24h Change","Market Cap"].map((head)=>(
<TableCell
style={{
color:"black",
fontWeight:700,
fontFamily:"Montserrat",
}}
key={head}
align={head==="Coin"? "": "right"}
>{head}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{handleSearch().map((row)=>{
const profit=row.price_change_percentage_24h>0;
return(
<TableRow onClick={()=>history(`/coins/${row.id}`)}
className={classes.row}
key={row.name}>
<TableCell
component="th"
scope="row"
style={{
display:"flex",
gap:15,
}}>
<img
src={row?.image}
alt={row.name}
height="50"
style={{
marginBottom:10
}}
/>
<div
style={{
display:"flex",
flexDirection:"column",
}}>
<span style={{
textTransform:"uppercase",
fontSize:22,
}}>
{row.symbol}
</span>
<span
style={{color:"darkgrey"}}>
{row.name}
</span>
</div>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
)}
</TableContainer>
</Container>
</ThemeProvider>
)
}
Any help would be appreciated as i am unable to resolve CORS header missing issue.
3
Answers
This means that "coingecko" has CORS headers disabled, possibly because of what you are doing i.e. embedding api calls to third party in your website without prior contact 🙂
CORS is a browser-side security construct. When your browser goes to make a "fetch" or "axios" call, it first sends an OPTIONS request to the URL that it will eventually make a GET/POST/PUT/… request for.
The browser looks at the response headers from the OPTIONS request. That is how the server tells the browser "it is safe to make a fetch from the following sites: ….." — in other words, "it is safe to call this server’s APIs from web pages that are coming from the following sites: …..". This mechanism is how a server is able to tell the browser which sites/pages are safe to call the APIs from.
For example, a bank’s server would indicate that it is only safe to call the APIs from the bank’s website (https://mybank.com). Anyone putting up a web page at some other address (e.g. https://myfakebank.com) could put calls to the bank’s API server, but the browser would throw a CORS error because the fake webpage would not be served from a "valid" site.
So in your case, look at the headers of the RESPONSE to the OPTIONS call of the API call in your browser’s NETWORK tab of the Dev Tools and see if it is giving the appropriate response (i.e.
Access-Control-Allow-Origin *
) in the event of "entering wrong credentials". If the web page you are trying to call the API from is not in the list of allowed origins, then your browser will not make the API call for its own (your own) safety.Let’s understand this error a bit:
You are trying to request a resource, which is at https://api.coingecko.com/ from http://localhost:3000. These two are on different domains/origins (one is at
coingecko.com
which is a server hosted somewhere and another is atlocalhost
which is nothing but your client machine).What is CORS?
CORS means CROSS ORIGIN RESOURCE SHARING.
What does it mean?
For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example,
fetch()
andXMLHttpRequest
follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers Source.If you are a Frontend Developer in your team and there is a separate Backend team, you need to request them to add the
http://localhost:3000
in the server as one of the whitelist origins. Once this is done from their end, you will be able to successfully request from yourlocalhost
.If you handle the Backend code as well, then you can simply add
http://localhost:3000
in the whitelist domains.PS – You can check multiple resources available on the internet on how to add the whitelist domains on a particular server.
Hope this helps you.