为什么我的axios呼叫未返回响应?

时间:2019-04-19 21:00:37

标签: node.js axios microservices

在下面的代码段中,我使用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();
})

1 个答案:

答案 0 :(得分:1)

一段时间后,我们发现微服务响应应该是:

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})
});