i tried fetching an API request but it is getting back this error Access to XMLHttpRequest at 'https://api.deezer.com/chart' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
the code
const {data, setData} = useState({});
const API = "https://api.deezer.com/chart";
useEffect(() => {
axios(API)
.then(response => {
setData(response);
console.log(data)
})
You have to understand that the CORS behavior is not an error — it’s a mechanism that’s working as expected in order to protect your users, you, or the site you’re calling. Check Link here
You can make it work by following different ways :
Temporary solution :
Disabling chrome security using
Windows : Windows + R --> chrome --disable-web-security --user-data-dir
MacOS : open -na Google\ Chrome --args --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials
Adding and using chrome extension : https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc/related?hl=en-GB
Permanent Solution :
If you don't have access to the api server which i can see you don't have you can call this API from your wrapper server it can be any server for eg : Node-express server or Java server (Adding basic node server example just call /getCharts api and you will get your desired results)
const express = require('express')
const app = express()
const port = 3000
const axios = require('axios');
app.get('/getCharts', (req, res) => {
const API = "https://api.deezer.com/chart";
axios(API)
.then(response => {
console.log(response.data)
res.json(response.data)
}).catch(err => {
res.send('errr!!!')
})
})
app.listen(port, () => console.log(`Server running on http://localhost:${port}`))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With