我最近开始学习 NestJS,因为它似乎是一个很棒的框架,可以帮助构建我的项目的后端。我需要学习但找不到的是一种从 3rd-party API 获取数据的方法。根据文档,它包装了 Axios,这很棒,因为我非常了解 Axios。我无法理解的是如何让它发挥作用。
出于学习目的,我正在尝试从 OpenWeatherMap.org 获取天气数据。当我搭建应用程序的脚手架时,我nest new weather-app按顺序使用并生成了天气模块、服务和控制器,以确保所有内容都与nest g <<<type of file>>> weather. 您可以放心地假设 myapp.module.ts正确weather.module.ts导入了 my 。此外,我的 OpenWeatherMap API 密钥会直接复制到我的.env.
这是我的weather.module.ts:
require('dotenv').config();
import { Module, HttpModule } from '@nestjs/common';
import { WeatherService } from './weather.service';
import { WeatherController } from './weather.controller';
@Module({
imports: [
HttpModule.register({
baseURL: 'api.openweathermap.org/data/2.5/weather',
params: {
appid: process.env.OPEN_WEATHER_KEY,
},
}),
],
providers: [WeatherService],
controllers: [WeatherController],
})
export class WeatherModule {}
Run Code Online (Sandbox Code Playgroud)
这是我的 …
我正在尝试构建一个映射给定数组的函数,然后对每个项目运行 axios 调用。完成后,我想返回映射的数组以在另一个函数中使用。
这是代码:
require('dotenv').config();
const axios = require('axios');
const consola = require('consola');
function getLeagues(listItems) {
const today = new Date();
const season = today.getMonth() >= 6 ? today.getFullYear() : today.getFullYear() - 1; // this gets the game ready for the new season every July 1st
// we will end up directly returning listItems.map once the issue is solved
const selectedLeagues = listItems.map(async (item) => {
const countryName = item.country;
const leagueName = item.league;
try {
const response = await …Run Code Online (Sandbox Code Playgroud)