【发布时间】:2021-06-08 06:57:53
【问题描述】:
Flipper Screenshot 我正在创建一个应用程序,单击登录按钮打开主页,但单击登录按钮后出现网络错误。仅当我通过应用程序运行时,此错误仍然存在,而我通过邮递员尝试 API 一切正常。我还尝试用我的 IP 地址替换 localhost 并在 android 清单中插入 android:usesCleartextTraffic="true" 但似乎没有任何效果
服务器.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const dbConfig = require("./app/config/db.config");
const app = express();
// var corsOptions = {
// origin: "http://localhost:8081"
// };
app.use(cors());
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
const db = require("./app/models");
const Role = db.role;
db.mongoose
.connect(`mongodb+srv://admin:<Mypassword>@cluster0.wmdoe.gcp.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
// routes
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "moderator"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'moderator' to roles collection");
});
new Role({
name: "admin"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'admin' to roles collection");
});
}
});
}
LoginScreen.js
/* eslint-disable no-shadow */
/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
import React, {useState, useEffect} from 'react';
import {TextInput, SafeAreaView,ScrollView,TouchableWithoutFeedback,Text, View, StyleSheet, Image} from 'react-native';
import Header from '../components/Header';
import {localizdStrings} from '../LocalizedConstants';
import { useNavigation } from '@react-navigation/native';
import CheckBox from '@react-native-community/checkbox';
import LinearGradient from 'react-native-linear-gradient';
import { SocialIcon } from 'react-native-elements';
import AsyncStorage from '@react-native-community/async-storage';
import GradientHeader from 'react-native-gradient-header';
import LocalizedStrings from 'react-native-localization';
import { showMessage } from 'react-native-flash-message';
import API from '../Config/API';
import axios from 'axios';
const LoginScreen = ({props}) => {
const navigation = useNavigation();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [toggleCheckBox, setToggleCheckBox] = useState(false);
const showErrorMessage = (message,type) => {
return showMessage({
message: message,
type: type,
color: '#ffffff',
fontSize: 14,
fontWeight: 'bold',
backgroundColor: '#0C254B',
});
};
const ValidateEmail = (inputText) => {
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputText.match(mailformat)) {
return true;
}
else {
return false;
}
};
const validate = async () =>{
if (email === '' || email === undefined || email === null) {
return showErrorMessage("Email can't be blank",'danger');
}
else if (ValidateEmail(email) === false) {
return showErrorMessage('Enter a valid Email address','danger');
}
else if (password === '' || password === undefined || password === null) {
return showErrorMessage("Password can't be blank",'danger');
}
else {
// const data = JSON.stringify({
// 'email': email,
// 'password': password,
// });
const options = {
method: 'post',
headers:{'Content-type': 'application/json'},
url: 'http://localhost:8080/api/auth/signin',
data: {
email: email,
password: password,
},
transformResponse: [(data) => {
return data;
}]
};
const res = await axios(options).then((res)=>{
if (res.data.success === true){
//navigation.navigate('Auth');
navigation.navigate('Home');
// navigation.navigate('Service',{screen:'Doppler'});
//showErrorMessage(response.data.message,'success')
}
console.log(res.status);
}).catch((error)=> {
console.log(error);
});
}
};
return (
<SafeAreaView style={styles.outerContainer}>
<View style={{flex:1}}>
<Header />
<ScrollView style={styles.scrollView}>
<TextInput
placeholder= {localizdStrings.EmailOrMobile}
style={styles.TextInput}
onChangeText={(email) => setEmail(email)}
value={email}
keyboardType = {'email-address'}
autoCapitalize = "none"
autoCorrect = {false}
/>
<TextInput
placeholder= {localizdStrings.Password}
style={styles.TextInput}
onChangeText={(password) => setPassword(password)}
value={password}
autoCapitalize = "none"
returnKeyType={'done'}
secureTextEntry={true}
autoCorrect = {false}
/>
<View style={{flexDirection:'row', marginLeft:20, width:380, padding:10}}>
<View style={{flexDirection:'row', justifyContent:'flex-start',alignItems:'center'}}>
<View style={styles.rememberMe}>
<CheckBox
disabled={false}
value={toggleCheckBox}
tintColors={{true: '#ff0000'}}
onValueChange={(newValue) => setToggleCheckBox(newValue)}
/>
<Text>{localizdStrings.RememberMe}</Text>
</View>
</View>
<View style={{flexDirection:'row', justifyContent:'flex-end',alignItems:'center', marginLeft:50 }}>
<View style={styles.forgetPass}>
<Text style={{color:'grey'}}>{localizdStrings.ForgetThePassword}</Text>
</View>
</View>
</View>
<TouchableWithoutFeedback onPress={() => validate()}>
<LinearGradient start={{x: 1, y: 0}} end={{x: 0, y: 0}} colors={['#29B6F6', '#29B6F6', '#0231C1']} style={styles.gradientStyle}>
<View style={styles.Loginbutton}>
<Text style={{fontWeight:'bold', fontSize:20, color:'white'}}>{localizdStrings.Login}</Text>
</View>
</LinearGradient>
</TouchableWithoutFeedback>
<View style={styles.quickAcess}>
<Text style={{fontWeight:'bold', marginTop:5}}> {localizdStrings.OrQuickAccessWith} </Text>
<View style={{ margin:5}}>
<TouchableWithoutFeedback >
<View style={styles.button}>
<Image source={require('../images/facebook.png')}
style={styles.socialIcon}
/>
<Text style={styles.socialLoginText}>{localizdStrings.Facebook}</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback>
<View style={styles.button}>
<Image source={require('../images/google.png')}
style={styles.socialIcon}
/>
<Text style={styles.socialLoginText}>{localizdStrings.Google}</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={()=> navigation.navigate('RegisterScreen')}>
<Text style={{marginLeft:95,marginRight:120, fontWeight:'bold', fontSize:18}}>{localizdStrings.CreateANewAccount}</Text>
</TouchableWithoutFeedback>
<View style={{marginLeft:150,marginRight:150}}>
<Image source={require('../images/color_logo.png')} style={{resizeMode:'contain',height:80, width:100}} />
<Image source={require('../images/labelwhite.png')} style={{resizeMode:'contain', height:80, width:100}} />
</View>
</View>
</View>
</ScrollView>
</View>
</SafeAreaView>
);
};
export default LoginScreen;
const styles = StyleSheet.create({
outerContainer:{
flex:1,
},
Loginbutton: {
alignItems: 'center',
paddingLeft: 60,
paddingRight:60,
paddingBottom:10,
paddingTop:10,
borderRadius:20,
marginBottom:10,
marginLeft: 40,
marginRight: 40,
height:50,
},
socialLoginText:{
color:'#00838F',
//marginLeft:-50,
paddingLeft:40,
},
socialIcon:{
marginRight:50,
marginLeft:-50,
},
scrollView: {
backgroundColor: 'white',
marginTop:100,
},
text: {
fontSize: 42,
},
TextInput: {
height: 50,
flex: 1,
paddingLeft: 20,
paddingRight: 20,
marginLeft: 40,
marginRight: 40,
borderColor: '#0277BD',
borderRadius: 30,
borderWidth: 1,
marginBottom:5,
marginTop:40,
},
rememberMe:{
flexDirection:'row',
alignItems:'center',
padding:10,
marginLeft: 5,
},
forgetPass:{
flexDirection:'row',
alignItems:'center',
padding:10,
},
gradientStyle:{
alignItems: 'center',
borderRadius:20,
marginBottom:10,
marginLeft: 40,
marginRight: 40,
height:50,
},
quickAcess:{
alignItems:'center',
},
button: {
alignItems: 'center',
backgroundColor: 'white',
paddingLeft: 60,
paddingRight:60,
paddingBottom:10,
paddingTop:10,
borderWidth:1,
borderColor:'#0277BD',
borderRadius:8,
flexDirection:'row',
margin:15,
},
});
控制台出错
[错误:网络错误]
【问题讨论】:
-
如果您在 chrome 检查器中调试应用程序,您是否看到调用的响应是什么?你能分享一下吗?您必须启用登录到检查器的请求,我使用这种方法 - stackoverflow.com/a/42952086/518341
-
或者,您也可以使用 Flipper 来查看它们。
-
我已经附上了flipper的截图
-
使用服务器的 IP 地址代替 localhost。将其更改为 localhost:8080/api/auth/signin 类似于 192.168.x.x:8080/api/auth/signin
标签: react-native axios mobile-application