How fix issue 'Blocked by CORS - No 'Access-Control-Allow-Origin' header'

Access to XMLHttpRequest at 'https://pro-api.coinmarketcap.com/v2/tools/price-conversion' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
CartModal.tsx?t=1695060428915:119 Error - AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
axios.js?v=d21b1d92:1511 GET https://pro-api.coinmarketcap.com/v2/tools/price-conversion net::ERR_FAILED
Access to XMLHttpRequest at 'https://pro-api.coinmarketcap.com/v2/tools/price-conversion' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
CartModal.tsx?t=1695060428915:119 Error - AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
axios.js?v=d21b1d92:1511 GET https://pro-api.coinmarketcap.com/v2/tools/price-conversion net::ERR_FAILED
I run my client on localhost:8000 I run my server on localhost:3000 I use React + Vite + TypeScript + express + nodemon + cors + dotenv + Node.js CartModal.tsx
useEffect(() => {
const fetchPriceConversion = async () => {
try {
const response = await axios.get('https://pro-api.coinmarketcap.com/v2/tools/price-conversion', {
headers: {
'X-CMC_PRO_API_KEY': import.meta.env.VITE_COINMARKETCAP_PUBLIC,
},
});
console.log('response -', response);
} catch (error) {
console.log('Error -', error);
}
};
useEffect(() => {
const fetchPriceConversion = async () => {
try {
const response = await axios.get('https://pro-api.coinmarketcap.com/v2/tools/price-conversion', {
headers: {
'X-CMC_PRO_API_KEY': import.meta.env.VITE_COINMARKETCAP_PUBLIC,
},
});
console.log('response -', response);
} catch (error) {
console.log('Error -', error);
}
};
server.ts
const baseURL = process.env.NODE_ENV === 'production' ? 'https://23-store.vercel.app' : 'http://localhost:8000';

/* server set up */
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors({
origin: [`${baseURL}`,'https://pro-api.coinmarketcap.com/v2/tools/price-conversion'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Access-Control-Allow-Origin', 'Origin', 'X-Requested-With', 'Accept', 'x-client-key', 'x-client-token', 'x-client-secret', 'Authorization'],
credentials: true
}))
app.use(express.static('public'));
const baseURL = process.env.NODE_ENV === 'production' ? 'https://23-store.vercel.app' : 'http://localhost:8000';

/* server set up */
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors({
origin: [`${baseURL}`,'https://pro-api.coinmarketcap.com/v2/tools/price-conversion'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Access-Control-Allow-Origin', 'Origin', 'X-Requested-With', 'Accept', 'x-client-key', 'x-client-token', 'x-client-secret', 'Authorization'],
credentials: true
}))
app.use(express.static('public'));
I tried this
app.use(cors())
app.use(cors())
And go the same error
1 Reply
Nikita
NikitaOP16mo ago
ChatGPT4 helped me solve it like this (I'm still don't understand what was the issue - I tried to change app.post to app.get) CartModal.tsx
const convertUSDToETHQuery = userCartStore.products
.filter((product: IProduct) => product.on_stock > 0)
.map((product: IProduct) => ({
price: product.price,
quantity: product.quantity
}))
.map(item => `amount=${encodeURIComponent(item.price * item.quantity)}`)
.join('&');



useEffect(() => {
const fetchPriceConversion = async () => {
try {
const response = await axios.get(
`${baseBackendURL}/coinmarketcap?${convertUSDToETHQuery}&symbol=USD&convert=ETH`
);
console.log(140,'response -', response);
setETHPrice(response.data.data[0].quote.ETH.price)
} catch (error) {
console.log('Error -', error);
}
};

fetchPriceConversion();
}, []);
const convertUSDToETHQuery = userCartStore.products
.filter((product: IProduct) => product.on_stock > 0)
.map((product: IProduct) => ({
price: product.price,
quantity: product.quantity
}))
.map(item => `amount=${encodeURIComponent(item.price * item.quantity)}`)
.join('&');



useEffect(() => {
const fetchPriceConversion = async () => {
try {
const response = await axios.get(
`${baseBackendURL}/coinmarketcap?${convertUSDToETHQuery}&symbol=USD&convert=ETH`
);
console.log(140,'response -', response);
setETHPrice(response.data.data[0].quote.ETH.price)
} catch (error) {
console.log('Error -', error);
}
};

fetchPriceConversion();
}, []);
server.ts
app.get('/coinmarketcap', async (req: Request, res: Response) => {
try {
const { amount, symbol, convert } = req.query;

const response = await axios.get(
`https://pro-api.coinmarketcap.com/v2/tools/price-conversion?amount=${amount}&symbol=${symbol}&convert=${convert}&CMC_PRO_API_KEY=${process.env.VITE_COINMARKETCAP_PUBLIC}`
);

res.status(200).json(response.data);
} catch (error) {
console.log('Error -', error);
res.status(500).json({ error: 'An error occurred while fetching data' });
}
});
app.get('/coinmarketcap', async (req: Request, res: Response) => {
try {
const { amount, symbol, convert } = req.query;

const response = await axios.get(
`https://pro-api.coinmarketcap.com/v2/tools/price-conversion?amount=${amount}&symbol=${symbol}&convert=${convert}&CMC_PRO_API_KEY=${process.env.VITE_COINMARKETCAP_PUBLIC}`
);

res.status(200).json(response.data);
} catch (error) {
console.log('Error -', error);
res.status(500).json({ error: 'An error occurred while fetching data' });
}
});
About Cross Origin - I need to do API request in on my backend server
Want results from more Discord servers?
Add your server