reactjs - Twitter API 获取请求返回 CORS 错误
问题描述
所以我一直在尝试在我一直在开发的 React 应用程序中使用 Twitter AP https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/quick-start。我正在使用fetch
API 来简单地访问快速入门教程中提到的端点。
每次我尝试在浏览器中点击端点时,都会出现以下错误:
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 时,我可以正确获取数据。我认为这必须是我使用fetch
API 的方式,但我没有看到任何在线示例来解决此问题。
这是代码:
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: include
HTTPS 请求,但我仍然遇到 CORS 问题。
解决方案
Twitter API 不支持 CORS。有关更多信息,请参阅此问题:Twitter API 授权在浏览器中失败 CORS 预检
推荐阅读
- fastlane - 有没有办法在没有 Fastlane 的相应应用程序的情况下创建捆绑标识符?
- python - 重命名默认的 django 表
- webrtc - 使用openvidu进行视频会议几秒钟后,MacBook中的相机将被冻结
- r - 使用列号而不是列名的 T 检验
- azure - 如何在 Azure SQL 中维护内存中的表副本?
- networking - ikev2 vpn连接
- r - R:列出具有扩展名和名称的目录中的文件
- android - Ionic React Native - 请求出错:/storage/emulated/0/Download/newPicture.png:打开失败:EACCES(权限被拒绝)
- powershell - Powershell:使用完整路径访问 Outlook 文件夹
- typescript - 如何在 React hooks-Typescript 中定义泛型数组类型?