获取天气---百度API,JSONP实现跨域请求

一、安装Jsonp

npm install jsonp --save

二、封装组件 

 建一个axios文件夹,创建index.js文件


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.message);
                }
             })
         })
     }
}

三、调用 


import React from 'react'
import { Row,Col } from 'antd';
import './index.less'
import axios from '../../axios'
export default class Header extends React.Component{
    state={}
    componentWillMount(){
        this.getWeatherAPIData();
    }
    getWeatherAPIData(){
        let city = '北京';
        axios.jsonp({
            url:'http://api.map.baidu.com/telematics/v3/weather?location='+encodeURIComponent(city)+'&output=json&ak=3p49MVra6urFRGOT9s8UBWr2'
        }).then((res)=>{
            if(res.status == 'success'){
                let data = res.results[0].weather_data[0];
                this.setState({
                    dayPictureUrl:data.dayPictureUrl,
                    weather:data.weather
                })
            }
        })
    }
    render(){
        return (
            <div className="header">
                 <img src={this.state.dayPictureUrl} alt=""/>
                 <span className="weather-detail">
                       {this.state.weather}
                 </span>     
        )
    }
}
发布了139 篇原创文章 · 获赞 27 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/chunchun1230/article/details/104366198
今日推荐