API 请求错误 - 请求的资源上不存在“Access-Control-Allow-Origin”标头

我尝试获取 API 请求,但它正在返回此错误 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' 标头出现在请求的资源上。

编码

const {data, setData} = useState({});
    const API = "https://api.deezer.com/chart";
    useEffect(() => {
        axios(API)
        .then(response => {
            setData(response);
            console.log(data)

        }) 
stack overflow API request error - No 'Access-Control-Allow-Origin' header is present on the requested resource
原文答案

答案:

作者头像
const url = "https://api.deezer.com/chart";
const config = {
   url,
   headers: {
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
    }
}

const {data, setData} = useState({});

    useEffect(() => {
        axios(config)
        .then(response => {
            setData(response);
            console.log(data)

        })
   }  //closing bracket required
); //closing bracket required

你需要像这样发送你的标题。或者你可以设置 axios 全局默认 header axios default header

在您的 API 方面,您需要激活 CORS

// if it is node api
const cors = require('cors');
app.use(cors());

相关问题