【发布时间】:2019-04-20 06:58:50
【问题描述】:
在下面的代码段中,我使用 axios 调用了一个微服务。
app.get('/api/user/microservice/signin', async (req, res) => {
console.log('USER SIGNIN BEGINS')
try {
const user = await axios.post('http://localhost:4210/usermicroservice/signin', req.body)
console.log('USER CONTROLLER user from mongo ', user)
res.send(user);
} catch (error) {
throw error;
}
});
调用目标函数,从数据库中检索数据,但结果永远不会到达调用函数。他们的系统只是挂起。
被调用函数:
app.post('/usermicroservice/signin', async (req, res) => {
console.log('\n*** USER MICROSERVICE SIGNIN CALLED ***')
let user = await UserMicroservice.signin(res, req.body);
console.log('user from mongo ', user)
// res.status(200).json({user})
return user;
});
UserMicrosevice.signin() 返回值:
if (await PasswordUtil.check(user.password, existingUser.password) == true) {
existingUser.token = PasswordUtil.generateAccessToken(existingUser, user.password);
console.log('existingUser token', existingUser.token)
console.log('existingUser', existingUser)
delete existingUser.password;
let credentials = { name: existingUser.name, email: existingUser.email, token: existingUser.token };
return credentials;
}
CORS:
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
})
【问题讨论】:
-
DevTools 会发出一些错误吗?能不能在检索到用户后下断点,看看接下来会发生什么?
-
检索用户后,我将结果记录到控制台。它看起来不错。然后我返回用户。
-
Axios以一种非常具体的方式返回值,Response对象应该有一个data属性,该属性内部应该是您想要的结果。我看到您将微服务的响应注释为 JSON,那里有什么问题? -
res.json(user) 将结果发送给邮递员,而不是调用函数。
-
当然,我明白了,但由于您从应用程序中调用了
endpoint,因此在我看来,您应该将值作为JSON或满足您需求的值返回。跨度>
标签: node.js axios microservices