eggjs 使用高德地图查询天气

eggjs yekong

eggjs 使用高德地图查询天气

创建文件weatcher

app/controller/weatcher.js

'use strict';

const Controller = require('egg').Controller;
const axios = require('axios');

class weatcherController extends Controller {
  async getWeather() {
    const { ctx } = this;
    var data = null;
    var config = {
      method: 'get',
      url: 'https://api.map.baidu.com/weather/v1/?district_id=' + ctx.query.code + '&data_type=all&ak=your ak',
      headers: {
        'Content-Type': 'application/json',
      },
    };
    await axios(config)
      .then(function(response) {
        data = response.data;
      })
      .catch(function(error) {
        data = error;
        return error;
      });
    ctx.body = data;
  }
}

module.exports = weatcherController;

路由配置

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  // 获取天气
  router.get('/api/weatcher/', controller.weatcher.getWeather);
};

喜欢