How to fix TypeError: Cannot read property 'post' of undefined on Axios with Nestjs cronjob
How to fix TypeError: Cannot read property 'post' of undefined on Axios with Nestjs cronjob
我尝试使用 cron 调度程序每 15 秒获取一次身份验证令牌(测试目的)cron 应该调用 auth 端点但我得到 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;
}
Cron 表达式不适用于请求范围的提供程序,因为可能 运行 在请求的上下文之外。因此,所有依赖项都以 undefined
的形式出现。要解决此问题,您需要一个非请求范围的提供程序。
我尝试使用 cron 调度程序每 15 秒获取一次身份验证令牌(测试目的)cron 应该调用 auth 端点但我得到 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;
}
Cron 表达式不适用于请求范围的提供程序,因为可能 运行 在请求的上下文之外。因此,所有依赖项都以 undefined
的形式出现。要解决此问题,您需要一个非请求范围的提供程序。