-1

I wrote those code but give some error: Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin

What will I can for those codes ? Thank you so much for helping...

import React, {useEffect, useState} from 'react';

function App() {
    const [coins,setCoins] = useState([]);
    const API_URL = 'https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest';

    const getCoins = (API) => {
        fetch(API, {
            "method": "GET",
            "headers": {
                "X-CMC_PRO_API_KEY": "b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c",
                "content-type": "application/json",
                "accept": "application/json",
                'Access-Control-Allow-Origin':'*'
            }
        })
        .then(response => {
            console.log(response);
        })
        .catch(err => {
            console.log(err);
        });
    }

    useEffect(() => {
        getCoins(API_URL);
    }, []);

  return (
    <div>
        {coins.map(coin => (
            <div>{coin.id}</div>
        ))}
    </div>
  );
}

export default App;
  • This isn't related to React but you can check the [proxy part for CRA documentation](https://create-react-app.dev/docs/proxying-api-requests-in-development/) if you used it to create your project. If not you can check the Webpack's proxy documentation or any other tool you used there. Since you are not the one managing the API part, you should either use a backend to make the request or use a development proxy as I suggested. – devserkan Oct 05 '20 at 13:10
  • not work with cra documentation I don't understand and tried with Axios but not worked useEffect(() => { //getCoins(LAST_URL); axios.get(LAST_URL,{headers: {'Access-Control-Allow-Origin':'*'}}).then(res => { setCoins(res.data); }).catch(error => console.log(error)); }); – NikolayAndrv Oct 06 '20 at 00:16
  • You are not the one managing the API and what are you doing there does not work. You need to use proper poxy. – devserkan Oct 06 '20 at 11:46

2 Answers2

0

This simply means that CORS are not enabled on backend/server-side.

Piyush Rana
  • 631
  • 5
  • 8
0

Pls. make sure if Access-Control-Allow-Origin is allowed at API server. For ex. if you're using nginx to host API's, then following line should be present in the nginx conf file.

location / {
add_header 'Access-Control-Allow-Origin' '*';
}

Similar config can be added for apache as well.