react中使用jsonp调用百度天气API,高德API

安装cnpm install jsonp --save

以下是封装的代码

import JsonP from 'jsonp';


export default class Axios {
    static jsonp(options){
        return new Promise((resolve, reject) => {
            JsonP(options.url, {
                param: 'callback'
            }, function (err, response) {
                if (response.status === 'success') {
                    resolve(response);
                } else {
                    reject(response.messsage);
                }
            })
        })
    }
 
在组件中使用,必须先引用
 
import Axios from '../../axios';
 
getWeatherApiDate() {
        Axios.jsonp({
            // 以前的天气百度ak  3p49MVra6urFRGOT9s8UBWr2 特别注意: 新用户没有百度地图免费api的权限
            url: 'http://api.map.baidu.com/telematics/v3/weather?location=上海&output=json&ak=3p49MVra6urFRGOT9s8UBWr2'
            // 高德的ak d325c2029eb25fb18127449297f12cfb 
            // url: 'https://restapi.amap.com/v3/weather/weatherInfo?city=深圳&key=d325c2029eb25fb18127449297f12cfb'
        }).then((res) => {
            console.log(res);
            if(res.status === 'success'){
                let data = res.results[0].weather_data[0];
                this.setState({
                    dayPictureUrl:data.dayPictureUrl,
                    weather:data.weather
                })
            }
        })
    }
 
componentDidMount(){
        this.getWeatherApiDate();
    }
 
 
 
 
 
 
 
 
 
 

 

posted @ 2020-04-06 21:53  奋斗的骚年20200220  阅读(245)  评论(0)    收藏  举报