Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API request error - No 'Access-Control-Allow-Origin' header is present on the requested resource

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)

        }) 
like image 841
Paschal Avatar asked Jan 24 '23 21:01

Paschal


1 Answers

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 :

  1. 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

  2. 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}`))
like image 129
Ashu Kharbanda Avatar answered Feb 12 '23 10:02

Ashu Kharbanda