【发布时间】:2021-01-25 17:14:12
【问题描述】:
我正在构建一个应用程序,用户可以在其中将博客文章发布到主页。现在,我只检索不是由登录用户发布的帖子。下面是前端的axios请求:
//Get user token
getUser() {
const token = this.props.location.state.token;
if (token) {
this.setState({ token: token });
Axios.get('http://localhost:3000/api/posts', {
headers: {
'auth-token': token,
},
})
.then((res) => {
this.setState({ id: res.data._id });
this.getPosts(res.data._id);
})
.catch((err) => {
console.log(err);
throw err;
});
}
}
//Get specific posts
getPosts(id) {
Axios.get(`http://localhost:3000/api/posts/all/${id}`)
.then((res) => {
console.log(res);
this.setState({ posts: res.data });
})
.catch((err) => {
console.log(err.message);
throw err;
});
}
componentDidMount() {
this.getUser();
}
getToken() 函数成功获取正确的用户和相关 id。然后我将 id 传递给我的 getPosts 函数,该函数在后端向该路由发出 get 请求:
// GET POSTS FROM OTHER USERS
router.get('/all/:id', async (req, res) => {
try {
console.log('GET POSTS FROM OTHER USERS');
console.log(req.params);
const user = await User.find({ _id: req.params });
console.log(user);
const posts = await Post.find({ email: { $ne: user[0].email } });
console.log(posts);
res.send(posts);
} catch (err) {
res.send(err);
}
});
为什么我的回复中没有返回任何数据?我知道我正在走路线并且猫鼬查询写得正确。我缺少一些异步行为吗?
【问题讨论】:
标签: reactjs express mongoose axios mongoose-schema