【发布时间】:2020-10-25 10:44:24
【问题描述】:
我正在使用MERN 堆栈创建一个网站,但是我不知道如何将数据获取到需要从后端授权的前端,我试图通过控制台记录问题,它向我显示了HTML我的登录页面,即使我已登录。任何将不胜感激,非常感谢。
我的后端代码:
router.get("/questions", ensureAuthenticated, (req, res) => {
math = Math.floor(Math.random() * 3) + 1;
Security.findOne({
user: req.user.id
}, (err, user) => {
if (err) {
console.log(err);
}
if (math === 1) {
res.send({
question: user.firstQuestion
});
} else if (math === 2) {
res.send({
question: user.secondQuestion
});
} else {
res.send({
question: user.thirdQuestion
});
}
});
});
我的前端代码:
class QuestionForm extends Component {
constructor(props) {
super(props);
this.state = {
data: ''
}
}
componentDidMount() {
axios.get("http://localhost:5000/users/questions")
.then((res) => {
this.setState({
data: res.data
});
}).catch((err) => console.log(err));
}
render() {
return <h1 > {
this.state.data
} < /h1>
}
}
【问题讨论】:
标签: node.js reactjs express axios mern