如何在ReactJS中的http:// localhost:3000 /和TMDB api之间启用CORS?

问题描述

我遇到无法从TMDB API获取数据的错误

CORS策略已阻止从源“ http:// localhost:3000”访问“ https://api.themoviedb.org/3”处的XMLHttpRequest:没有“ Access-Control-Allow-Origin”标头出现在请求的资源上。

axios.js设置

import axios from "axios";  
const instance = axios.create({
    baseURL: "https://api.themoviedb.org/3",})  
export default instance;

request.js设置:

const API_KEY = "xxx";  
const request = {  
  fetchTrending: `/trending/all/week?api_key=${API_KEY}&language=en-US`,fetchNetflixOriginal: `/discover/tv?api_key=${API_KEY}&with_networks=213`,}  
export default request;

App.js

useEffect(() => {
        //if [],run once when row load,and dont run again
        console.log("rrrrsd >>> ",typeof(fetchUrl))

        async function fetchData(){
            const response = await axios.get(fetchUrl,{
                headers:{
                    'Access-Control-Allow-Origin': '*',}
            }).then(function (response){
                console.log('response >>>>',response.data)
            }).catch(function (error){
                if(error.response){
                    console.log('response error >>>',error.response.headers)
                }
                else if(error.request){
                    console.log('error request >>>',error.request)
                }
                else{
                    console.log('message error >>>',error.message)
                }
            })

        }
        fetchData()
    },[fetchUrl])

请帮助我在TMDB API和ReactJS localHost之间启用CORS

解决方法

使用Google Chrome扩展名,例如(CORS Domain)或(允许CORS) 昨天我遇到了同样的问题,扩展程序已解决