[英]MERN router.get request returning undefined
So, I'm trying to use a get request to find the email of a user and display the information on screen.因此,我尝试使用获取请求来查找用户的 email 并在屏幕上显示信息。 To do this, I set a local storage item with the user's email and am trying to reference this in my api call.
为此,我使用用户的 email 设置了一个本地存储项,并尝试在我的 api 调用中引用它。 However, on the back-end side of things, when I try and send the email through an axios call it doesn't make it to the back-end where I can do anything with it.
但是,在后端方面,当我尝试通过 axios 调用发送 email 时,它不会到达后端,我可以用它做任何事情。 I'm getting a status code 500 error along with this
TypeError: Cannot read property 'then' of undefined
.我收到状态代码 500 错误以及此
TypeError: Cannot read property 'then' of undefined
。
This is my router.get function that's throwing the error这是我的 router.get function 抛出错误
router.get("/user", function(req, res) {
console.log("id hit");
console.log(req.data);
console.log(req.params.email);
db.User
.getUserByEmail(req.params.email)
.then((dbModel) => res.json(dbModel))
.catch((err) => res.status(422).json(err));
});
This is my getUserByEmail function这是我的 getUserByEmail function
module.exports.getUserByEmail = function (email, callback) {
console.log("getUserByEmail", email)
var query = { email: email };
console.log(query);
User.findOne(query, callback);
};
This is my front-end API axios call这是我的前端 API axios 调用
getUser: function(email) {
console.log("API EMAIL: ",email);
return axios.get("/api/users/user/", email);
}
And this is my componentDidMount on the page I want to display the information on这是我要显示信息的页面上的 componentDidMount
componentDidMount() {
const userEmail = localStorage.getItem("userEmail");
this.setState({
email: userEmail
}, () => {
console.log(this.state.email);
API.getUser(this.state.email)
.then(data => {
this.setState({
firstName: data.firstName,
lastName: data.lastName,
})
})
})
}
I'm able to reference the email on the front-end side of things, but once it gets to the back-end, everything's undefined.我可以在前端引用 email,但是一旦它到达后端,一切都未定义。 Any help is appreciated.
任何帮助表示赞赏。
module.exports.getUserByEmail = function (email, callback) {
console.log("getUserByEmail", email)
var query = { email: email };
console.log(query);
User.findOne(query, callback);
};
This function doesn't return anything you need to return something from it.这个 function 不会返回任何你需要从中返回的东西。
you could do你可以做
return user.findOne(query, callback);
as long as user.findOne returns something and if its mongoose or mongo its probably a proimse.只要 user.findOne 返回一些东西,如果它的 mongoose 或 mongo 它可能是一个承诺。
Also you need the route to be你也需要路线是
router.get("/user/:email", function(req, res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.