I am working on a Cryptocurrency tracker using React.JS and API. In my App.js I am having an error while running it on localhost.
App.js
code:-
import React, {useState, useEffect} from 'react';
import axios from 'axios'
import './App.css';
function App() {
const [coins, setCoins] = useState([])
useEffect(() => {
axios
.get(
'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false'
)
.then(res => {
setCoins(res.data)
// console.log(res.data);
}).catch(error => console.log(error))
}, []);
index.js
code:-
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Error :- Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false . (Reason: CORS header 'Access-Control-Allow-Origin' missing)
To avoid cors issues in your dev environment you can use a proxy provided by eg http-proxy-middleware
( https://www.npmjs.com/package/http-proxy-middleware )
With it installed you can create a file named setupProxy.js in your /src
directory like:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
app.use(
'/coingecko',
createProxyMiddleware({
target: 'https://api.coingecko.com/api/v3',
changeOrigin: true,
pathRewrite: {
'/coingecko': '/',
},
})
);
};
In your axios request, you will be able to use:
useEffect(() => {
axios
.get(
'/coingecko/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false'
)
.then(res => {
setCoins(res.data)
// console.log(res.data);
}).catch(error => console.log(error))
}, []);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.