How to fix TypeError: Cannot read property 'post' of undefined on Axios with Nestjs cronjob

帅比萌擦擦* 提交于 2020-08-10 19:37:15

问题


I tried using cron scheduler to get authentication token every 15 sec(Test purpose) the cron is supposed to call the auth endpoint but I got Exception has occurred: TypeError: Cannot read property 'post' of undefined

 @Cron(CronExpression.EVERY_15_SECONDS)
    async handleCron() {
        //const Primetimeauth = this.PrimetimeAuth()

        const primeAuth = await this.httpService.post('https://clients.com/api/auth', {
            "username": process.env.username,
            "password": process.env.password
        }).toPromise();

        if (primeAuth.status != 200) {
            throw new HttpException({
                message: `Vending Authentication Failed`,
                statusCode: primeAuth.status
            }, HttpStatus.BAD_REQUEST);
        }

        const data = primeAuth.data;

        await this.PrimetimeAuthToken.updateOne({ "_id": "3dtgf1341662c133f0db71412drt" }, {
            "$set":
            {
                token: data.token,
                tokenExpirationTime: data.expires,
                timeTokenReceived: new Date
            }
        });

        return data;
    }

回答1:


Cron expressions do not work with Request scoped providers, due to possibly being run outside of the context of the request. Due to this, all dependencies come in as undefined. To fix this, you'll need a non-request-scoped provider.



来源:https://stackoverflow.com/questions/63039361/how-to-fix-typeerror-cannot-read-property-post-of-undefined-on-axios-with-nes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!