react-native网络请求

2023-08-24  本文已影响0人  微风_10a5

网络请求,使用的是第三方网络接口- 和风天气(有免费,也有商用的接口),大家可以去注册,登录一下,创建一个项目,会得到一个key,然后就可以免费使用了

和风天气-对应的文档:
https://dev.qweather.com/docs/api/weather/weather-daily-forecast/

测试一下接口--请求三天的天气预报

可以直接用浏览器来测试(写可以用postman软件来测试),

https://devapi.qweather.com/v7/weather/3d?location=116.41,39.92&key=ab016705d280420b8d72f5c6892901dc

结果如下:


image.png

转化为json格式

{
  "code": "200",
  "updateTime": "2021-11-15T16:35+08:00",
  "fxLink": "http://hfx.link/2ax1",
  "daily": [
    {
      "fxDate": "2021-11-15",
      "sunrise": "06:58",
      "sunset": "16:59",
      "moonrise": "15:16",
      "moonset": "03:40",
      "moonPhase": "盈凸月",
      "moonPhaseIcon": "803",
      "tempMax": "12",
      "tempMin": "-1",
      "iconDay": "101",
      "textDay": "多云",
      "iconNight": "150",
      "textNight": "晴",
      "wind360Day": "45",
      "windDirDay": "东北风",
      "windScaleDay": "1-2",
      "windSpeedDay": "3",
      "wind360Night": "0",
      "windDirNight": "北风",
      "windScaleNight": "1-2",
      "windSpeedNight": "3",
      "humidity": "65",
      "precip": "0.0",
      "pressure": "1020",
      "vis": "25",
      "cloud": "4",
      "uvIndex": "3"
    },
    {
      "fxDate": "2021-11-16",
      "sunrise": "07:00",
      "sunset": "16:58",
      "moonrise": "15:38",
      "moonset": "04:40",
      "moonPhase": "盈凸月",
      "moonPhaseIcon": "803",
      "tempMax": "13",
      "tempMin": "0",
      "iconDay": "100",
      "textDay": "晴",
      "iconNight": "101",
      "textNight": "多云",
      "wind360Day": "225",
      "windDirDay": "西南风",
      "windScaleDay": "1-2",
      "windSpeedDay": "3",
      "wind360Night": "225",
      "windDirNight": "西南风",
      "windScaleNight": "1-2",
      "windSpeedNight": "3",
      "humidity": "74",
      "precip": "0.0",
      "pressure": "1016",
      "vis": "25",
      "cloud": "1",
      "uvIndex": "3"
    },
    {
      "fxDate": "2021-11-17",
      "sunrise": "07:01",
      "sunset": "16:57",
      "moonrise": "16:01",
      "moonset": "05:41",
      "moonPhase": "盈凸月",
      "moonPhaseIcon": "803",
      "tempMax": "13",
      "tempMin": "0",
      "iconDay": "100",
      "textDay": "晴",
      "iconNight": "150",
      "textNight": "晴",
      "wind360Day": "225",
      "windDirDay": "西南风",
      "windScaleDay": "1-2",
      "windSpeedDay": "3",
      "wind360Night": "225",
      "windDirNight": "西南风",
      "windScaleNight": "1-2",
      "windSpeedNight": "3",
      "humidity": "56",
      "precip": "0.0",
      "pressure": "1009",
      "vis": "25",
      "cloud": "0",
      "uvIndex": "3"
    }
  ],
  "refer": {
    "sources": [
      "QWeather",
      "NMC",
      "ECMWF"
    ],
    "license": [
      "QWeather Developers License"
    ]
  }
}

测试结果与文档一致,代表接口正常,下面我们就在代码进行请求

代码中请求接口

直接在代码中,用fetch请求
    const byFetch = () => {
        let appKey = "ab016705d280420b8d72f5c6892901dc"
        let cityLocation = "116.41,39.92"
        let url = `https://devapi.qweather.com/v7/weather/3d?location=${cityLocation}&key=${appKey}`

        fetch(url, {
            method: 'GET'
        })
            .then((response) => response.json())//response.json()返回是一个Promiss对象,才是我们需要的数据
            .then((data) => {
                console.log(data)
                Alert.alert('success', '请求成功')
            }).catch((error) => {
                Alert.alert('error', JSON.stringify(error))
            })
    }

需要注意的地方是fetch(url, { method: 'GET' })返回的response,并不是我们想要的,而是要将其转化为json,//response.json()返回是一个Promiss对象,才是我们需要的数据,所以后面可以接着.then()
结果如下

image.png
封装api,用fetch请求
api.js文件代码
// 定义一个常量,存储appKey
const appKey = "ab016705d280420b8d72f5c6892901dc"

// 定义一个箭头函数,接收城市经纬度作为参数
export const getWeatherData = async (cityLocation) => {
    // 根据城市经纬度获取天气数据
    let url = `https://devapi.qweather.com/v7/weather/3d?location=${cityLocation}&key=${appKey}`
    try {
        // 使用await等待响应
        let response = await fetch(url, {
            method: 'GET'
        })
        // 使用await等待数据
        let data = await response.json()
        // 返回天气数据
        return data
    } catch (error) {
        // 处理错误
        console.error(error)
    }
}
        let cityLocation = "116.41,39.92"
        getWeatherData(cityLocation)
            .then((result) => {
                console.log(result)
                console.log(result.daily)

                Alert.alert('ByFetch 成功', '请求成功')
            }).catch((error) => {
                Alert.alert('error', JSON.stringify(error))
            })
image.png

这样我们就成功请求,并成功收到回复,收到数据

封装api,用axios请求
export const getWeatherDataByAxios = async (cityLocation) => {
    console.log("getWeatherDataByAxios------")
    // 根据城市经纬度获取天气数据
    let url = `https://devapi.qweather.com/v7/weather/3d?location=${cityLocation}&key=${appKey}`
    try {
        // 使用axios发送请求,并使用await等待数据

        let result = await axios.get(url)
        // 返回天气数据
        return result.data
    } catch (error) {
        // 处理错误
        console.error(error)
    }
}

需要注意的地方是,我们需要的数据在返回的result中的data中,所以看到代码中是这样返回的result.data

       let cityLocation = "116.41,39.92"
        getWeatherDataByAxios(cityLocation)
            .then((result) => {
                console.log(result)
                console.log(result.daily)

                Alert.alert('getWeatherDataByAxios 成功', '请求成功')
            }).catch((error) => {
                Alert.alert('error', JSON.stringify(error))
            })
image.png

这样我们就成功请求,并成功收到回复,收到数据

api.js文件里面的完整代码如下

import axios from 'axios';
// 定义一个常量,存储appKey
const appKey = "ab016705d280420b8d72f5c6892901dc"

// 定义一个箭头函数,接收城市经纬度作为参数
export const getWeatherData = async (cityLocation) => {
    // 根据城市经纬度获取天气数据
    let url = `https://devapi.qweather.com/v7/weather/3d?location=${cityLocation}&key=${appKey}`
    try {
        // 使用await等待响应
        let response = await fetch(url, {
            method: 'GET'
        })
        // 使用await等待数据
        let data = await response.json()
        // 返回天气数据
        return data
    } catch (error) {
        // 处理错误
        console.error(error)
    }
}


// 定义一个箭头函数,接收城市经纬度作为参数
export const getWeatherDataByAxios = async (cityLocation) => {
    console.log("getWeatherDataByAxios------")
    // 根据城市经纬度获取天气数据
    let url = `https://devapi.qweather.com/v7/weather/3d?location=${cityLocation}&key=${appKey}`
    try {
        // 使用axios发送请求,并使用await等待数据

        let result = await axios.get(url)
        // 返回天气数据
        return result.data
    } catch (error) {
        // 处理错误
        console.error(error)
    }
}

测试文件home_screen.js里面的完整代码如下

//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button, Alert, axios } from 'react-native';
import MyLoading from './custom_component/loading'

import { getWeatherData, getWeatherDataByAxios } from './custom_component/api'
// create a component
const HomeScreen = ({ navigation }) => {


    goToDetailScreen = () => {
        navigation.navigate('Detail')
    }

    const byFetch = () => {

        let cityLocation = "116.41,39.92"
        getWeatherData(cityLocation)
            .then((result) => {
                console.log(result)
                console.log(result.daily)

                Alert.alert('ByFetch 成功', '请求成功')
            }).catch((error) => {
                Alert.alert('error', JSON.stringify(error))
            })



        // let appKey = "ab016705d280420b8d72f5c6892901dc"
        // let cityLocation = "116.41,39.92"
        // let url = `https://devapi.qweather.com/v7/weather/3d?location=${cityLocation}&key=${appKey}`

        // fetch(url, {
        //     method: 'GET'
        // })
        //     .then((response) => response.json())//response.json()返回是一个Promiss对象,才是我们需要的数据
        //     .then((data) => {
        //         console.log(data)
        //         Alert.alert('success', '请求成功')
        //     }).catch((error) => {
        //         Alert.alert('error', JSON.stringify(error))
        //     })
    }


    const byAxios = () => {

        let cityLocation = "116.41,39.92"
        getWeatherDataByAxios(cityLocation)
            .then((result) => {
                console.log(result)
                console.log(result.daily)

                Alert.alert('getWeatherDataByAxios 成功', '请求成功')
            }).catch((error) => {
                Alert.alert('error', JSON.stringify(error))
            })
    }

    return (
        <View style={styles.container}>
            <Text>HomeScreen</Text>
            <Button title='to detail screen' onPress={goToDetailScreen}></Button>
            <MyLoading title="请稍后。。。" onTap={() => {
                console.log("loading... tapped")
            }}></MyLoading>

            <Button title='to get weather data by axios' onPress={byAxios}></Button>
            <Button title='to get weather data by fetch' onPress={byFetch}></Button>

        </View>
    );
};

// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f5f5f5',
    },
});

//make this component available to the app
export default HomeScreen;

结尾

今天RN 的分享就到这里喽,小伴们,觉得有点用的话,或者已经看到这里面来的请点个赞加关注吧~~ 后续分享更多有关RN Flutter和移动端原生开发相关的文章。欢迎在下面留言交流。

上一篇 下一篇

猜你喜欢

热点阅读