【问题标题】:React App - Issue with CORS - access to fetch has been blocked by cors policyReact App - CORS 问题 - 访问 fetch 已被 cors 策略阻止
【发布时间】:2023-01-14 03:36:20
【问题描述】:

我正在通过使用 react 来制作应用程序,它会从 twitter API 捕获数据

那是我的代码

import {useEffect, useState, useContext} from 'react'
import {Link, useParams, useNavigate, useLocation} from 'react-router-dom'



export default function Home(){

    const [content, setContent] = useState();

    const token = 'here is the required token but i cant show you that'
    
    useEffect(() => {
        const url = 'https://api.twitter.com/1.1/search/tweets.json?q=something';
        fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`,
            }
        })

        .then((response) => {
            if(response.status === 404){
                console.log('404');
            }
            else{
                console.log(response.status)
                console.log('3')
            }
        })

        .then((data) => {

            console.log("abba")
            console.log(data)
            setContent(data)
        })

        

        .catch((e) => {
            console.log(e.message);
        })

    }, [])

    return(<div>{content}</div>)

}

我遇到了这种类型的错误

Access to fetch at 'https://api.twitter.com/1.1/search/tweets.json?q=ewron' from origin 'http://localhost:3000' has been blocked by CORS policy:

当我使用邮递员使用相同的令牌捕获数据时,一切正常

我试图找到解决方案,但每个人都指的是同一台机器上的后端集。我该如何解决?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    CORS 策略是一项重要功能,可防止其他外部网站访问 API。

    有些 API 启用了 CORS,有些则禁用了它。白名单将根据该 API 开发人员的需求/偏好进行定制。

    Twitter 可能会允许 twitter.com 使用 Twitter 的公共 api。连同他们使用的其他域。或者可能根本没有,我知道他们的 CORS 策略是如何设置的。他们肯定会在 API 文档中对此有所了解。

    它适用于邮递员的原因是您不是从浏览器中运行的网站调用它,而是从您的计算机调用它 - 它充当一种“后端服务器”。这不违反 CORS 政策,因此它适合您。

    请务必注意,您的浏览器正在执行 CORS 策略——理论上,API 不知道请求是来自网站还是服务器。您的浏览器或多或少会告诉您。所以它不是安全的保证或任何东西,但它是一个相当不错的防范措施。

    所有这一切都是说——如果您想使用他们的 API,您需要设置自己的路由并在您自己的后端服务器/API 上进行前端调用,然后调用 twitter API .这就是我猜其他人试图告诉你的。

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 2021-03-18
      • 2021-10-27
      • 2021-04-15
      • 2020-11-23
      • 2019-12-18
      • 2019-04-28
      • 1970-01-01
      • 2021-10-05
      相关资源
      最近更新 更多