React Native跨平台鸿蒙开发实战系列:项目引入axios增加Header参数

张开发
2026/4/14 6:41:25 15 分钟阅读

分享文章

React Native跨平台鸿蒙开发实战系列:项目引入axios增加Header参数
一个基于 Promise 来管理 http 请求的简洁、易用且高效的代码封装库。通俗一点来讲它是一个前端替代Ajax的一个东西可以使用它发起http请求接口功能它是基于Promise的相比于Ajax的回调函数能够更好的管理异步操作。Axios是一个基于Promise的HTTP客户端库专门用于在浏览器和Node.js环境中处理网络请求。它通过封装XMLHttpRequest浏览器端和http模块Node.js端为开发者提供了统一、简洁的API来发送HTTP请求。相比于原生的Fetch APIAxios在易用性和功能完整性方面都有明显优势特别是在请求配置、拦截器处理和错误管理上表现突出。在HTTP请求中请求头Headers扮演着至关重要的角色它们作为元数据信息控制着请求和响应的处理方式。比如Content-Type头部告诉服务器请求体的数据格式Authorization头部用于身份验证Accept头部则指定客户端期望接收的响应内容类型。这些头部信息直接影响着API调用的成功与否。设置Header头设置请求头的方式非常灵活可以根据不同场景选择合适的方法。全局配置适用于那些在所有请求中都需要携带的通用头部比如认证令牌。通过axios.create()创建实例并设置defaults.headers.common属性就能为所有通过该实例发送的请求自动添加指定的头部信息。这种方式特别适合在企业级应用中统一管理认证信息。对于特定的请求方法可以通过实例配置来设置默认头部。比如针对POST请求可以预先设置Content-Type为application/json这样每次使用该实例发起POST请求时都会自动使用这个配置。这种粒度控制让不同类型的请求能够拥有各自合适的默认头部设置。单个请求级别的头部配置提供了最大的灵活性。在具体的请求调用中通过config参数的headers属性直接设置这种方式会覆盖全局和实例级别的同名头部配置适用于那些需要特殊处理的个别请求场景。在实际开发中身份验证是最常见的请求头使用场景。Bearer Token认证模式被广泛采用通过在Authorization头部携带访问令牌来验证用户身份。这种模式简单易用安全性也相对较好是现代Web应用中的主流选择。内容类型协商也是请求头的重要功能。通过Accept头部客户端可以明确告知服务器自己能够处理的响应格式比如application/json或application/xml。同时Content-Type头部则告诉服务器请求体的数据格式确保双方能够正确解析数据。除了这些基本用法请求头还可以用于传递自定义业务信息。比如语言偏好、设备类型、API版本等这些信息虽然不直接控制HTTP协议行为但对业务逻辑的实现至关重要。请求头的设置还涉及到一些高级特性。比如CSRF防护通过X-CSRF-Token头部来防止跨站请求伪造攻击。还有缓存控制通过Cache-Control头部来管理客户端和中间节点的缓存行为。importReactfromreact;import{View,Text,Dimensions,StyleSheet,Image,TextInput,TouchableOpacity,Alert}fromreact-native;import{Modal,ModalContent,ModalPortal}fromreact-native-modals;import{createStaticNavigation}fromreact-navigation/native;import{createNativeStackNavigator}fromreact-navigation/native-stack;//获取屏幕的宽高constscreenWidthMath.round(Dimensions.get(window).width);constscreenHightMath.round(Dimensions.get(window).height);importaxiosfromaxios;constAppStylesStyleSheet.create({wrap:{width:100%,height:screenHight,backgroundColor:#85BDFF},title:{width:100%,height:72,fontFamily:OPPOSans, OPPOSans,fontWeight:normal,paddingTop:50,fontSize:36,color:#304057,lineHeight:72,textAlign:center,fontStyle:normal},banner:{paddingTop:50,paddingRight:32,paddingLeft:32,},bannerItem:{paddingTop:10,display:flex,flexDirection:row,alignItems:center,justifyContent:center,width:50%,},loginBox:{position:relative,width:100%,paddingTop:29,paddingLeft:20,paddingRight:20,borderTopRightRadius:30,borderTopLeftRadius:30,backgroundColor:#F2F8FF,flex:1},loginBoxCode:{marginTop:20,position:relative,width:100%,},loginBoxCodeBtn:{position:absolute,right:4,top:4,width:110,height:40,lineHeight:40,borderRadius:10,backgroundColor:#1669E3,textAlign:center,fontWeight:bold,fontSize:14,color:#FFFFFF,},loginBtn:{position:absolute,left:20,bottom:30,width:100%,height:48,lineHeight:48,borderRadius:10,backgroundColor:#1669E3,textAlign:center,fontWeight:bold,fontSize:14,color:#FFFFFF,}})functionHomePath(){const[phone,onChangePhone]React.useState();const[code,onChangeCode]React.useState();const[visible,setVisible]React.useState(false);constsubmitLogin(){console.log(submitLogin,phone,code);varregex/^1[3-9]\d{9}$/;if(!regex.test(phone)){Alert.alert(请输入正确的手机号码);return;}varregex/^\d{6}$/;if(!regex.test(code)){Alert.alert(请输入正确的验证码);return;}// setVisible(true);axios.get(https://xxxxx.com/id_type?t1764427207873,{headers:{Content-Type:application/json,projectid:xxxx}}).then(function(response){console.log(get id_type success:,JSON.stringify(response));Alert.alert(JSON.stringify(response));// navigation.navigate(IndexPath)}).catch(function(error){console.log(error);});}return(View style{AppStyles.wrap}Text style{AppStyles.title}鸿蒙ReactNative系统/TextView style{AppStyles.banner}View style{{display:flex,flexDirection:row,justifyContent:space-between}}View style{AppStyles.bannerItem}Image style{{width:27,height:27}}source{require(./images/checked.png)}/ImageText style{{paddingLeft:4}}实时业绩便捷查询/Text/ViewView style{AppStyles.bannerItem}Image style{{width:27,height:27}}source{require(./images/checked.png)}/ImageText style{{paddingLeft:4}}订单状态轻松把控/Text/View/ViewView style{{display:flex,flexDirection:row,justifyContent:space-between}}View style{AppStyles.bannerItem}Image style{{width:27,height:27}}source{require(./images/checked.png)}/ImageText style{{paddingLeft:4}}宣传数据全程管理/Text/ViewView style{AppStyles.bannerItem}Image style{{width:27,height:27}}source{require(./images/checked.png)}/ImageText style{{paddingLeft:4}}海量素材一站转发/Text/View/View/ViewImage style{{width:289,height:182,display:flex,alignSelf:center,margin:20}}source{require(./images/login-bg.png)}/ImageView style{AppStyles.loginBox}TextInput style{{width:100%,height:48,borderRadius:10,backgroundColor:#FFFFFF,paddingLeft:16,paddingRight:16,fontSize:14,color:#304057}}placeholder请输入手机号onChangeText{onChangePhone}value{phone}keyboardTypenumericmaxLength{11}/TextInputView style{AppStyles.loginBoxCode}TextInput style{{width:100%,height:48,borderRadius:10,backgroundColor:#FFFFFF,paddingLeft:16,paddingRight:16,fontSize:14,color:#304057}}placeholder请输入验证码onChangeText{onChangeCode}value{code}keyboardTypenumericmaxLength{6}/TextInputText style{AppStyles.loginBoxCodeBtn}获取验证码/Text/ViewTouchableOpacity style{AppStyles.loginBtn}onPress{submitLogin}Text style{{fontSize:14,color:#FFFFFF,lineHeight:48,textAlign:center,fontWeight:bold}}登陆/Text/TouchableOpacity/ViewModalPortalModal visible{visible}onTouchOutside{(){setVisible(false)}}onSwipeOut{()setVisible(false)}ModalContentText登录成功欢迎使用我们的应用。/TextText手机号{phone}/TextTouchableOpacity style{{marginTop:20,padding:10,backgroundColor:#1669E3,borderRadius:5}}onPress{()setVisible(false)}Text style{{color:#FFFFFF,textAlign:center}}确定/Text/TouchableOpacity/ModalContent/Modal/ModalPortal/View);}接下来通过打包命令npn run harmony将reactNative的代码打包成为bundle这样可以进行在开源鸿蒙OpenHarmony中进行使用。接下来将bundle文件复制到鸿蒙的项目工程中进行引入然后正常打包后可以看到以下的运行效果可以看到自从加上了header头后我们请求数据成功了。欢迎大家加入开源鸿蒙跨平台开发者社区一起共建开源鸿蒙跨平台生态。

更多文章