获取天气---百度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>     
        )
    }
}

 

然后就实现了跨域请求

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值