axios Twitter用户使用React.js搜索以显示姓名、关注者、关注者等

3b6akqbq  于 2023-01-20  发布在  iOS
关注(0)|答案(2)|浏览(163)

我对react.js还是个新手,我只是在尝试一些我能想到的随机项目,其中之一是在react.js中创建一个搜索引擎,通过在搜索栏中输入用户名来查找Twitter上的用户,结果将使用Twitter API显示他们的详细信息。然而,当我这样做时,我在控制台中遇到了以下错误:Error ocuring
App.js:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const App = ({ username }) => {

  const [user, setUser] = useState({});
  const [tweets, setTweets] = useState({});
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
        try {
            const { data: user } = await axios.get(`https://api.twitter.com/1.1/users/show.json?screen_name=${username}`, {
              method : "GET",
                headers: {
                    Authorization: `Bearer <YOUR_TOKEN>`
                }
            });
            const { data: tweets } = await axios.get(`https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=${username}&count=200`, {
              method : "GET",
                headers: {
                    Authorization: `Bearer <YOUR_TOKEN>`
                }
            });
            setUser(user);
            setTweets(tweets);
        } catch (error) {
            setError(error);
        }
    };
    fetchData();
  }, [username]);

  if (error) {
    return <div>An error occurred: {error.message}</div>;
  }

  return (
    <div>
      <h1>{user.name}</h1>
      <p>Username: {user.screen_name}</p>
      <p>Followers: {user.followers_count}</p>
      <p>Following: {user.friends_count}</p>
      <p>Bio: {user.description}</p>
      <p>Date Joined: {user.created_at}</p>
      <p>Pinned Tweet: {user.status ? user.status.text : 'No Pinned Tweet'}</p>
      <p>Total Tweets: {user.statuses_count}</p>
    </div>
  );
};

export default App;
    • 更新**

我已经将搜索框特性添加到代码中,但仍然得到相同的errors

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const TWITTER_API_URL = 'https://api.twitter.com/1.1/users/search.json';

function App() {
  const [username, setUsername] = useState('');
  const [userData, setUserData] = useState({});
  const [searchValue, setSearchValue] = useState('');

  useEffect(() => {
    if (searchValue) {
      axios
        .get(TWITTER_API_URL, {
          params: {
            q: searchValue,
            count: 1
          },
          headers: {
            'Authorization': 'Bearer YOUR_BEARER_TOKEN'
          }
        })
        .then(response => {
          setUsername(response.data[0].screen_name);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }, [searchValue]);

  useEffect(() => {
    if (username) {
      axios
        .get(`https://api.twitter.com/1.1/users/show.json?screen_name=${username}`, {
          headers: {
            'Authorization': 'Bearer YOUR_BEARER_TOKEN'
          }
        })
        .then(response => {
          setUserData(response.data);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }, [username]);

  return (
    <div>
      <input
        type="text"
        placeholder="Search by name"
        value={searchValue}
        onChange={e => setSearchValue(e.target.value)}
      />
      {username && (
        <div>
          <p>Username: {username}</p>
          <p>Name: {userData.name}</p>
          <p>Following: {userData.friends_count}</p>
          <p>Followers: {userData.followers_count}</p>
          <p>Bio: {userData.description}</p>
          <p>Date Joined: {userData.created_at}</p>
          <p>Pinned Tweet: {userData.status.text}</p>
          <p>Total Tweets: {userData.statuses_count}</p>
        </div>
      )}
    </div>
  );
}

export default App;

我将感激任何帮助给解决这个问题。谢谢。

p8ekf7hl

p8ekf7hl1#

我建议您将const fetchData = async () => { ...移到useEffect()之外,这听起来可能很愚蠢,但是对于Authorization: Bearer <YOUR_TOKEN>,您是否使用实际令牌更改了<YOUR_TOKEN>?最后,您不需要method : "GET",因为您正在执行axios.get( ...
请输入验证码:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const App = ({ username }) => {

  const [user, setUser] = useState({});
  const [tweets, setTweets] = useState({});
  const [error, setError] = useState(null);

 
    const fetchData = async () => {
        try {
            const { data: user } = await axios.get(`https://api.twitter.com/1.1/users/show.json?screen_name=${username}`, {           
                headers: {
                    Authorization: `Bearer <YOUR_TOKEN>`
                }
            });
            const { data: tweets } = await axios.get(`https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=${username}&count=200`, {
                headers: {
                    Authorization: `Bearer <YOUR_TOKEN>`
                }
            });
            setUser(user);
            setTweets(tweets);
        } catch (error) {
            setError(error);
        }
    };

 useEffect(() => {
    fetchData();
  }, [username]);

  if (error) {
    return <div>An error occurred: {error.message}</div>;
  }

  return (
    <div>
      <h1>{user.name}</h1>
      <p>Username: {user.screen_name}</p>
      <p>Followers: {user.followers_count}</p>
      <p>Following: {user.friends_count}</p>
      <p>Bio: {user.description}</p>
      <p>Date Joined: {user.created_at}</p>
      <p>Pinned Tweet: {user.status ? user.status.text : 'No Pinned Tweet'}</p>
      <p>Total Tweets: {user.statuses_count}</p>
    </div>
  );
};

export default App;
iibxawm4

iibxawm42#

您看到的错误消息与CORS(跨源资源共享)有关,它阻止您在“http://localhost:3000”上运行的JavaScript代码向“www.example.com“发出请求https://api.twitter.com。
CORS是由Web浏览器实现的安全功能,可防止网页向提供该网页的域以外的其他域发出请求。
要解决此问题,您需要在服务器端设置CORS标头。“Access-Control-Allow-Origin”标头用于指定允许哪些域向服务器发出请求。您可以将此标头设置为“*”以允许任何域发出请求,也可以将其设置为运行应用程序的特定域,在您的情况下为“http://localhost:3000”。
您还可以使用代理服务器,以避免在尝试访问twitter的API时出现CORS问题。这意味着您的React应用程序将向服务器发送请求,然后服务器将请求转发给twitter的API。然后服务器将接收响应,并将其转发回您的React应用程序。这样,您的应用程序将永远不会被CORS策略阻止。因为请求来自服务器而不是直接来自应用程序。

相关问题