[英]XMLHttpRequest is not working on react native app
我正在使用 XMLHttpRequest api 从响应本机 android 应用程序中的服务器请求资源这是我的应用程序代码(客户端)
import React,{Component} from 'react';
import {Text,View,StyleSheet,TouchableOpacity} from 'react-native';
class Home extends Component
{
state={con:''}
show=()=>
{
alert("show function called");
var req=new XMLHttpRequest();
req.onreadystatechange=(e)=>
{
if(req.status==200 && req.readyState==4)
{
alert(req.responseText);
}
}
req.open("GET","http://localhost:3000/show_react");
req.send();
}
render()
{
return(
<View style={styles.container}>
<TouchableOpacity onPress={()=>this.show()} style={styles.box}><Text>Click</Text></TouchableOpacity>
<Text>{this.state.con}</Text>
</View>
);
}
}
export default Home;
const styles=StyleSheet.create({
box:
{
padding:10,
width:200,
marginTop:10,
backgroundColor:'rgba(215, 44, 149, 0.7)',
alignItems:'center'
},
container:
{
flexDirection:'row',
justifyContent:'center'
}
});
下面是我的简单 node.js 代码(服务器端),用于接受来自客户端的请求
app.get("/show_react",function(req,res){
console.log("show_react called");
res.send("hii react");
});
上述服务器端代码在浏览器请求时运行成功,但在客户端(react native app)请求时不起作用。 任何答案表示赞赏。
好吧...在客户端,我刚刚创建了一个按钮。 当触摸按钮时,显示功能被调用。 这个show函数将为运行在端口3000的localhost服务器创建一个新的XMLHttpRequest(localhost:3000 / show_react)。
如果您在react native应用程序中的请求URL实际上是localhost:3000/show_react
则您的问题是localhost
指向您的本地设备(即智能手机)。 需要从运行React Native应用程序的设备访问该URL。 尝试在设备(即智能手机)的Safari浏览器中浏览到URL
为了使用 Fetch,你必须使用 React-Native 中的 drop 来替代 Fetch; react-native 中的 Fetch API 是 XMLHttpRequest 的包装器。 我使用 react-native-blob-util 因为它使用 NativeModules 来实现 fetch。
我确实在追踪为什么我的 XMLHttpRequest 被我破坏了,但我没有找到原因。 我确实发现,而不是像 xhr.onload 这样的东西,我可以做 xhr.addEventListener('load', ()...) 它会起作用。 可能对未来的求职者有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.