如何通过UUID、ReactJs NodeJs正确获取(axios)



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

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

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

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

如何解决此问题?

那是我的收货和退货

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 schéma。

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

您的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解析器的方法来净化您的SQL请求。

由于您已登录,因此浏览器中的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;

最新更新