[英]Asynchronous function findOne returns "undefined"
I created a function to check if in my database a user exists according to the sub
parameter.我创建了一个函数来根据
sub
参数检查我的数据库中是否存在用户。 I would like my function to give me a true
or false
value.我希望我的函数给我一个
true
值或false
值。
Front-end :前端:
......
async function exist(sub) {
const result = await InfoDataService.get(sub)
alert(result.sub);
}
......
Controller :控制器:
// Find a User with sub
exports.findOne = (req, res) => {
const sub = req.params.sub;
User.findOne({sub})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message: "Error retrieving User with id=" +sub
});
});
};
Route :路线:
module.exports = app => {
const users = require("../controllers/user.controller.js");
const router = require("express").Router();
// Retrieve
router.get("/:sub", users.findOne);
app.use('/api/users', router);
};
InfoDataService :信息数据服务:
import http from "../http-common.js";
const get = sub => {
return http.get(`/users/${sub}`);
};
export default {
get,
};
http-common : http-common :
import axios from "axios";
export default axios.create({
method: 'GET',
baseURL: "http://localhost:8080/api",
});
If instead of result.sub
I use only result
I can retrieve the object, but if I try to access the .sub
property I get "undefined".如果我只使用
result
而不是result.sub
我可以检索对象,但是如果我尝试访问.sub
属性,我会得到“未定义”。
I noticed another thing that is probably related: the path for post is api/users
, while for get it is api/users/:sub
.我注意到另一件可能相关的事情: post 的路径是
api/users
,而 get 的路径是api/users/:sub
。 Checking the network I found that the asynchronous function makes the request to api/users/undefined
.检查网络我发现异步函数向
api/users/undefined
发出请求。 Where would the error be?错误在哪里?
Not sure if User.findOne({sub})
is correct, should maybe rather be a where clause there?不确定
User.findOne({sub})
是否正确,是否应该是 where 子句? { where: sub}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.