Yun*_*nus 7 android fetch react-native
我有一个由Nodejs处理的注册服务.此服务正在3001端口上运行.我尝试从React Native应用程序连接此服务.但总是回归
ReactNativeJS:[TypeError:网络请求失败]
我的组件和package.json代码如下.此外,我将URL localhost替换为127.0.0.1,它不起作用.当我从Postman测试后端服务正常工作.提供非常常见的异常网络错误,因此很难理解问题的根源.每个React Native开发人员都可以轻松应对此问题.那么问题是由React Native还是Android造成的?
import React, { Component } from 'react';
import {
TextInput,
ScrollView,
Alert,
TouchableHighlight,
Text,
StyleSheet
} from 'react-native';
export default class Register extends Component {
constructor(props) {
super(props);
this.onPress = this.onPress.bind(this);
}
componentDidMount() {
this.state = {
email: '',
password: '',
passwordRepetition: '',
error: '',
loading: false
};
}
onPress() {
fetch('http://127.0.0.1:3001/user/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
}),
}).then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
render() {
return (
<ScrollView>
<TextInput
style={{ height: 40 }}
placeholder="type@email.com"
onChangeText={email => this.setState({ email })}
/>
<TextInput
style={{ height: 40 }}
placeholder="veryhardpassword"
secureTextEntry
onChangeText={password => this.setState({ password })}
/>
<TextInput
style={{ height: 40 }}
placeholder="repetition of password"
secureTextEntry
onChangeText={passwordRepetition =>
this.setState({ passwordRepetition })
}
/>
<TouchableHighlight style={styles.button} onPress={this.onPress}>
<Text> Touch Here </Text>
</TouchableHighlight>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingHorizontal: 10
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10
},
countContainer: {
alignItems: 'center',
padding: 10
},
countText: {
color: '#FF00FF'
}
});
Run Code Online (Sandbox Code Playgroud)
的package.json
{
"name": "mobile",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.3.0-alpha.1",
"react-native": "^0.54.0"
},
"devDependencies": {
"babel-jest": "22.4.1",
"babel-preset-react-native": "4.0.0",
"eslint": "^4.18.2",
"eslint-plugin-react": "^7.7.0",
"jest": "22.4.2",
"react-test-renderer": "16.3.0-alpha.1"
},
"jest": {
"preset": "react-native"
}
}
Run Code Online (Sandbox Code Playgroud)
可能有2种情况来测试此问题。
关键点在命令下运行
$ adb反向tcp:3001 tcp:3001
模板:adb反向tcp:{APPLICATIONPORT} tcp:{APPLICATIONPORT}
第一种情况是pc内的ipconfig并找到本地IP地址,例如192.168.1.4。您的网址应为http://192.168.1.4:3001/用户/注册
如果使用仿真器,则应使用以下网址,例如http://10.0.2.2:3001/user/register
在运行adb reverse命令后,这些URL对我有用。
| 归档时间: |
|
| 查看次数: |
3489 次 |
| 最近记录: |