Skip to content

使用 nest 完成 天气预报

介绍

  • 利用和风天气用户中心完成一个天气预报

流程

  • 通过安装拼音的包获取和风城市的 id

  • 通过城市 id 获取和风天气的 API 获取城市天气

  • 通过 nest 完成接口的编写

  • 项目发送外部请求和利用第三方接口

前置

和风注册

  • 注册以后修改联系方式和点击控制台
  • 点击控制台创建项目
  • 创建项目名称
  • 创建凭据
  • 获取 APIKey 和使用场景
  • 获取你访问的 API 地址

和风最后 API 请求形式

  • 代码如下
bash
https://你自己的.qweatherapi.com/geo/v2/city/lookup?location=汉语拼音地名&key=你自己的apikey

获取天气

  • 获取城市 现在的天气
bash

https://你自己的.qweather.com/v7/weather/now?location=刚才获取到城市的id&key=你自己的apikey

Nest 使用拼音

安装

ts

npm install --save pinyin@alpha
npm install --save-dev @types/pinyin

使用

ts
import { Controller, Get, Query } from "@nestjs/common";
import { WeatherService } from "./weather.service";
import pinyin from "pinyin";
@Controller("weather")
export class WeatherController {
  constructor(private readonly weatherService: WeatherService) {}
  @Get("pinyin")
  async pinyin(@Query() query: any) {
    // 第二个参数就是pinyin的配置项,normal表示把带声调的汉字转换成不带声调的拼音
    return {
      data: pinyin(query.name, { style: "normal" }).join(""),
    };
  }
}
  • 访问的时候就是
bash
GET  http://127.0.0.1:5000/weather/pinyin?name=天津
Content-Type: application/json
  • 返回的就是拼音
bash
tianjin

Nest 使用 axios 发送数据

安装

ts

npm install --save @nestjs/axios axios

创建模块和服务

ts
nest g service axios
nest g module axios
  • axios.module.ts
ts
import { Module, Global } from "@nestjs/common";
import { AxiosService } from "./axios.service";

@Global()
@Module({
  providers: [AxiosService],
  exports: [AxiosService],
})
export class AxiosModule {}
  • axios.service.ts
ts
import { Injectable } from "@nestjs/common";
import axios, { AxiosInstance } from "axios";

@Injectable()
export class AxiosService {
  private readonly axiosInstance: AxiosInstance;

  constructor() {
    this.axiosInstance = axios.create({
      timeout: 10000, // 设置超时时间
    });
  }

  // get方法
  async get(url: string, config?: any) {
    return this.axiosInstance.get(url, config);
  }
}

使用

  • weather.service.ts
ts
import { Inject, Injectable } from "@nestjs/common";
import { CreateWeatherDto } from "./dto/create-weather.dto";
import { UpdateWeatherDto } from "./dto/update-weather.dto";
import { AxiosService } from "../axios/axios.service";
@Injectable()
export class WeatherService {
  @Inject()
  private readonly axiosService: AxiosService;
  create(createWeatherDto: CreateWeatherDto) {
    return "This action adds a new weather";
  }

  findAll() {
    return `This action returns all weather`;
  }

  findOne(id: number) {
    return `This action returns a #${id} weather`;
  }

  update(id: number, updateWeatherDto: UpdateWeatherDto) {
    return `This action updates a #${id} weather`;
  }

  remove(id: number) {
    return `This action removes a #${id} weather`;
  }

  // 获取天气
  async getweacher(pinyin) {
    console.log(pinyin);
    const result = await this.axiosService.get(
      `https://yyyyyy.qweatherapi.com/geo/v2/city/lookup?location=${pinyin}&key=xxxxx`
    );
    console.log(result.data);
    return result.data;
  }
}
  • weather.controller.ts
ts
import { Controller, Get, Query } from "@nestjs/common";
import { WeatherService } from "./weather.service";
import pinyin from "pinyin";
@Controller("weather")
export class WeatherController {
  constructor(private readonly weatherService: WeatherService) {}
  @Get()
  findAll() {
    return {
      data: this.weatherService.findAll(),
    };
  }

  @Get("pinyin")
  async pinyin(@Query() query: any) {
    // 第二个参数就是pinyin的配置项,normal表示把带声调的汉字转换成不带声调的拼音
    const result = await this.weatherService.getweacher(
      pinyin(query.name, { style: "normal" }).join("")
    );
    return {
      data: result,
    };
  }
}