【问题标题】:how to correctly get (axios) by UUID , ReactJs NodeJs如何通过 UUID 正确获取(axios),ReactJs NodeJs
【发布时间】:2020-07-30 17:50:17
【问题描述】:

我想解释一下我今天遇到的问题。

目前我正在登录, 我在我的个人资料中,在这里我想显示我的名字。

以下代码可以正常工作,只是它显示了在我的数据库中注册的所有使用情况。

我只希望能够显示与我的数据库中的 UID 对应的正确名称

我该如何解决这个问题?

这是我的get和return

class Profile  extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data:[]
    };
  }

  getRandom = async () => {
    const res = await axios.get(
      "https://joke.fr/api/profil"
    );

    this.setState({ data: res.data })
  }

  componentDidMount() {
    this.getRandom()
  }

  render() {
      return (
        <div>
        {this.state.data.map(data => <p>{data.name}</p>)}
        </div>
    )
  }
}

export default Profile;

那是我的路线是bdd

app.get('/api/profil', (req, res) => {
  connection.query('SELECT * from profil' , (err, results) => {
    if (err) {
      console.log(err);
      return res.status(500).send('Erreur lors de la récupération des employés');
    } else {
      console.log(results);
      return res.json(results);
    }
  });
});

最后一个是我的 BDD 架构。

{
  "id": 62,
  "name": "neff",
  "uid": "dycjibu96zgmzc0KpGAqxKiUsMu2"
}

【问题讨论】:

    标签: mysql node.js reactjs axios fetch


    【解决方案1】:

    您的 app.get 中需要另一个参数。我想当用户登录到您的应用程序时,您存储了他们的 UID。如果是这种情况,您可以使用:

    app.get('api/profil/:id', (req, res) => {
            const userId = req.params.id
            connection.query(`SELECT * from profil WHERE id = ${userId}` , (err, results) => {
              if (err) {
                console.log(err);
                return res.status(500).send('Erreur lors de la récupération des employés');
              } else {
                 console.log(results);
                 return res.json(results);
              }
           });
    })
    

    但我会推荐 body-parser 之类的东西来清理您的 SQL 请求。

    【讨论】:

      【解决方案2】:

      既然您已登录,那么您可能已将浏览器中的 UUID 或名称保存在本地存储中(这是最简单的方法)。这意味着您应该在您的后端发送一个GET 请求以获取基于 UUID 的 1 个配置文件。

      服务器端代码

      app.get('/api/profil/:name', (req, res) => {
        const { name } = req.params;
      
        connection.query(`SELECT * from profil where name=${name}`, (err, results) => {
          if (err) {
            console.log(err);
            return res.status(500).send('Erreur lors de la récupération des employés');
          } else {
            // This should be an object
            console.log(results); // This should be an object like {"id": 62, "name": "authUser"}
            return res.json(results);
          }
        });
      });
      

      客户端代码

      class Profile  extends Component {
        constructor(props) {
          super(props);
          this.state = {
            userProfile: null
          };
        }
      
        getUserProfile = async (userName) => {
          // Get the profile by passing the id to the URL.
          // Side note, you should handle errors here but for simplicity lets skip it.
      
          const res = await axios.get(
            `https://joke.fr/api/profil/${userName}`
          );
      
          // res.data should be an object like {"id": 62, "name": "authUser"}
          this.setState({ userProfile: res.data });
        }
      
        componentDidMount() {
          // You should have the id of the user after login
          // Let me assume you stored it in localstorage
          const user = localStorage.getItem("user");
          if (user) {
            const { id, name } = JSON.parse(user);
            // You can skip the localstorage part if you store the user's details in a different way and jump here by passing the ID/name to this function
            this.getUserProfile(name);
          }
        }
      
        render() {
          const { userProfile } = this.state;
      
          return (
            <div>
              {userProfile ? userProfile.name : "No user name"}
            </div>
          )
        }
      }
      
      export default Profile;
      
      

      【讨论】:

      • 嗨我有一个 404 错误,在邮递员上,在我的服务器上我只有“没有用户名”,我如何检查我的 UUID 是否在我的本地存储中。 ?
      • 好的,我检查了本地存储,另一方面,我确实有一个技巧,不是 UUID 名称是“authUser”,因为我使用 FIREBASE,这会改变什么吗?
      • 您可以将当前代码粘贴到 github gist.github.com/new 中吗?我会更快地调试问题,以了解您收到 404 的原因。并将您通过邮递员发送的请求的 URL 发送给我。
      • 我更新了代码,所以你可以发送名字而不是id,基本上没有太大区别,你只需要改变你服务器上的express url,sql查询和你从服务器发送的数据客户端。
      • 好的,这就是我的主旨gist.github.com/Neffou/8d4c2020b125b9884ff0b165e5f12b3d,你去看乱七八糟的时候不要惊慌^^我是初学者
      猜你喜欢
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 2020-06-04
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多