【发布时间】:2021-11-05 05:44:50
【问题描述】:
我有两个不同的 API URL。我可以使用 /api/current_user 获取当前用户的 ID 并保存到“currentuser”状态。我想从 MySQL 中获取所有 currentuser's。我的 API URL 有效。但我无法使用 currentuser 状态变量获取。
此链接返回当前用户的 ID。它有效。
useEffect(()=>{
fetch('http://localhost:8000/api/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then(res => res.json())
.then(json => {
setCurrentuser(json.id);
});
},[])
然后我想将该 ID 与 currentuser 状态一起使用。
Axios.request({
method: 'POST',
url: 'http://localhost:3001/api/post',
data: {
curus: `${currentuser}` // I'm trying to use currentuser state on here.
},
})
.then(response => {
return response.data;
})
.then(data => {
let tmpArray2 = []
const tmpArray = []
bla bla bla ...
最后请求载荷返回curus: ""
所以它有一个空值。我可以在返回函数中使用这个状态值。
这也是我节点服务器的 index.js:
app.post('/api/post', (req, res) => {
const currentt = req.body.curus
const sqlSelect = "SELECT * FROM messagestable WHERE sender='" + currentt + "' OR recipient ='" + currentt + "' ";
db.query(sqlSelect, (err, result) => {
res.send(result);
console.log(currentt)
});
})
我想从 MySQL 中获取所有消息,但只针对当前用户。不是所有用户的消息。你能帮帮我吗?非常感谢!
【问题讨论】:
-
给我更多的上下文:第一个填充
currentuser的 fecth 是在组件加载时完成的。但是当Axios.requestfill 被解雇的时候呢?点击按钮?在组件的加载?你把它写在组件的主体上? -
'currentuser' 状态是否与 Axios 请求处于相同的上下文中?对我来说,要么在定义当前用户状态之前启动 axios 请求,要么用户状态为 null,因为不在 Axios 请求组件上下文中。此外,您的服务器容易受到 SQL 注入的攻击,check this link
-
我在 useEffect() 中同时使用它们。他们接连而来。第一个是“ fetch('localhost:8000/api/current_user', {....”,第二个代码块是底部。
标签: reactjs axios react-hooks fetch