首页 > 解决方案 > 为什么我的 axios 调用没有返回响应?

问题描述

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

UserMicroservice.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();
})

标签: node.jsaxiosmicroservices

解决方案


过了一会儿,我们弄清楚了,微服务响应应该是:

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

推荐阅读