Koa端点始终返回404

时间:2018-09-25 03:25:21

标签: node.js typescript mongoose async-await koa

我遇到了一个问题,我认为呼叫返回得太早,并使我的响应始终是404-未找到消息。该条目是在数据库中完成的,因此据我所知,它正在尽早返回。我认为我已经等待了正确的部分,但是显然不是这样。我也尝试过在db.AddUser上等待,但是没有运气。

端点

//Post signup
public async SignUpAsync(ctx: Context) {
    try {
        let code = await SignUpVerification.GenerateCode();
        let user = await this.InfoFromRequest(ctx.request.body);
        user.Code = code;
        await db.AddUser(user);
        console.log('added db user');
        //await SignUpVerification.SendVerificationText(user.PhoneNumber, code)
        console.log('success message');
        ctx.body = 'Success';
    } catch (err) {
        ctx.status = 400;
        ctx.body = err;
    }
};

private async InfoFromRequest(requestBody: any) {
    return {
        Email: requestBody['email'],
        FirstName: requestBody['firstname'],
        MiddleName: requestBody['middlename'],
        LastName: requestBody['lastname'],
        Pwd: requestBody['pwd'],
        PhoneNumber: requestBody['phonenumber']
    } as IUserModel;
}

调用模型

async AddUser(newUser: IUserModel) {
    return await userModel.AddUser(newUser);
}

模型调用

async AddUser(newUser: IUserModel) {
    try {
        var userToSave = new User({
            name: {
                firstname: newUser.FirstName,
                middlename: newUser.MiddleName,
                lastname: newUser.LastName
            },
            email: newUser.Email,
            pwd: newUser.Pwd,
            code: newUser.Code,
            phonenumber: newUser.PhoneNumber
        });

        let result = await userToSave.save();
        console.log('New User saved');
        console.log(result);
    } catch (err) {
        throw new Error(err);
    }
}

方法生成从模型调用返回的代码

static async GenerateCode() {
    return await (Math.floor(Math.random() * 90000) + 10000).toString();
}

1 个答案:

答案 0 :(得分:0)

通过查看中间件中如何添加功能,Evert步入了正确的轨道。

之前

this.router.post(
            'login/',
            (ctx) => {
                this.controller.LoginAsync(ctx);
            }
        );

正确

this.router.post(
            'login/',
            async (ctx) => {
                await this.controller.LoginAsync(ctx);
            }
        );