天气api -跨域axios-jsonp -Promise封装

1.天气api

http://api.map.baidu.com/telematics/v3/weather?location=查询地区 &output=输出格式 &ak=开发者密钥

 url:'http://api.map.baidu.com/telematics/v3/weather?location='+encodeURIComponent(city)+'&output=json&ak=3p49MVra6urFRGOT9s8UBWr2'

//encodeURIComponent是中文转码;

2.封装jsonp

/jsonp(url, opts, fn)

1. npm install jsonp --save

2.yarn add jsonp --save

export default class Axios {

static jsonp(options) {  //定义静态jsonp方法  options传一个大对象

        return new Promise((resolve, reject) => {

            JsonP(options.url, {

                param: 'callback'  //jsonp一定要callback

            }, function (err, response) {

                if (response.status == 'success') {

                    resolve(response);

                } else {

                    reject(response.messsage);

                }

            })

        })

    }

}

 

其他组件调用

import axios from '../../axios'

  getWeatherAPIData(){

        let city = '北京';

        axios.jsonp({

            url:'http://api.map.baidu.com/telematics/v3/weather?location='+encodeURIComponent(city)+'&output=json&ak=3p49MVra6urFRGOT9s8UBWr2'    //encodeURIComponent转码

        }).then((res)=>{

            if(res.status == 'success'){

                let data = res.results[0].weather_data[0];

                this.setState({

                    dayPictureUrl:data.dayPictureUrl,

                    weather:data.weather

                })

            }

        })

    }

 

 

标签内调用

                                    

                                

                                

                                    {this.state.weather}

                                

 

 

 

 

你可能感兴趣的:(react,api,axios)