首页 > 解决方案 > Twitter API 获取请求返回 CORS 错误

问题描述

所以我一直在尝试在我一直在开发的 React 应用程序中使用 Twitter AP https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/quick-start。我正在使用fetchAPI 来简单地访问快速入门教程中提到的端点。

每次我尝试在浏览器中点击端点时,都会出现以下错误:

Access to fetch at 'https://api.twitter.com/2/users/by?user.fields=&usernames=trengriffin,awealthofcs,ReformedBroker,michaelbatnick,Wu_Tang_Finance&tweet.fields=author_id,created_at' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

但是,当我使用与邮递员相同的参数点击此 URL 时,我可以正确获取数据。我认为这必须是我使用fetchAPI 的方式,但我没有看到任何在线示例来解决此问题。

这是代码:

const endpointUrl = 'https://api.twitter.com/2/users/by?user.fields=&usernames=trengriffin,awealthofcs,ReformedBroker,michaelbatnick,Wu_Tang_Finance&tweet.fields=author_id,created_at';
const TwitterContainer: React.FC<ContainerProps> = () => {
   useEffect( () => {
      fetch(endpointUrl, {
         mode: 'cors',
         credentials: 'include',
         headers: {
            "Authorization": `Bearer ${token}`
         },

      }).then(res => res.json())
          .then(console.log)
          .catch(console.error);

我不确定为什么我仍然收到错误。根据fetch文档,您必须使用credentials: includeHTTPS 请求,但我仍然遇到 CORS 问题。

标签: reactjstwitterfetch

解决方案


Twitter API 不支持 CORS。有关更多信息,请参阅此问题:Twitter API 授权在浏览器中失败 CORS 预检


推荐阅读