注册时触发AxiosError: Network Error,该如何排查解决?
注册页面无法连接后端API写入MongoDB的问题
问题描述
开发注册页面时,尝试向MongoDB添加数据失败。前端使用axios.post("http://localhost:8000/register")时直接弹出AxiosError;改为metro bundler的8081端口时请求能发送但数据无法写入MongoDB(已知8081是metro端口,和后端8000端口无关)。
后端代码
const express = require("express"); const bodyParser = require("body-parser"); const mongoose = require("mongoose"); const passport = require("passport"); const LocalStrategy = require("passport-local").Strategy; const app = express(); const port = 8000; const cors = require("cors"); app.use(cors()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(passport.initialize()); const jwt = require("jsonwebtoken"); mongoose .connect( "mongodb+srv://<user>:<password>@cluster0.03lvgad.mongodb.net/", { useNewUrlParser: true, useUnifiedTopology: true, } ) .then(() => { console.log("Success"); }); app.listen(port, () => { console.log("Server is running"); }); const User = require("./models/user"); const Message = require("./models/message"); //endpoint for Signup app.post("/register", (req, res) => { const { name, email, password, image } = req.body; //new user const newUser = new User({ name, email, password, image }); //save user to database newUser .save() .then(() => { res.status(200).json({ message: "User registered succesfully" }); }) .catch((err) => { console.log("Error in register", err); res.status(500).json({ message: "Error! User not registered" }); }); });
前端代码
import { StyleSheet, Text, View, TextInput, KeyboardAvoidingView, Pressable, Alert, } from "react-native"; import React, { useState } from "react"; import { useNavigation } from "@react-navigation/native"; import axios from "axios"; const RegisterScreen = () => { const [email, setEmail] = useState(""); const [name, setName] = useState(""); const [password, setPassword] = useState(""); const [image, setImage] = useState(""); const navigation = useNavigation(); const handleRegister = () => { const user = { name: name, email: email, password: password, image: image, }; // send a POST request to the backend API to register the user axios .post("http://localhost:8000/register", user) .then((response) => { console.log(response); Alert.alert( "Registration successful", "You have been registered Successfully" ); setName(""); setEmail(""); setPassword(""); setImage(""); }) .catch((error) => { Alert.alert( "Registration Error", "An error occurred while registering" ); console.log("registration failed", error); }); }; return ( <View style={{ flex: 1, backgroundColor: "white", padding: 10, alignItems: "center", }} > <KeyboardAvoidingView> <View style={{ marginTop: 100, justifyContent: "center", alignItems: "center", }} > <Text style={{ color: "#4A55A2", fontSize: 17, fontWeight: "600" }}> Register </Text> <Text style={{ fontSize: 17, fontWeight: "600", marginTop: 15 }}> Register To your Account </Text> </View> <View style={{ marginTop: 50 }}> <View style={{ marginTop: 10 }}> <Text style={{ fontSize: 18, fontWeight: "600", color: "gray" }}> Name </Text> <TextInput value={name} onChangeText={(text) => setName(text)} style={{ fontSize: email ? 18 : 18, borderBottomColor: "gray", borderBottomWidth: 1, marginVertical: 10, width: 300, }} placeholderTextColor="black" placeholder="Enter your name" /> </View> <View> <Text style={{ fontSize: 18, fontWeight: "600", color: "gray" }}> Email </Text> <TextInput value={email} onChangeText={(text) => setEmail(text)} style={{ fontSize: email ? 18 : 18, borderBottomColor: "gray", borderBottomWidth: 1, marginVertical: 10, width: 300, }} placeholderTextColor="black" placeholder="enter Your Email" /> </View> <View style={{ marginTop: 10 }}> <Text style={{ fontSize: 18, fontWeight: "600", color: "gray" }}> Password </Text> <TextInput value={password} onChangeText={(text) => setPassword(text)} secureTextEntry={true} style={{ fontSize: email ? 18 : 18, borderBottomColor: "gray", borderBottomWidth: 1, marginVertical: 10, width: 300, }} placeholderTextColor="black" placeholder="Password" /> </View> <View style={{ marginTop: 10 }}> <Text style={{ fontSize: 18, fontWeight: "600", color: "gray" }}> Image </Text> <TextInput value={image} onChangeText={(text) => setImage(text)} style={{ fontSize: email ? 18 : 18, borderBottomColor: "gray", borderBottomWidth: 1, marginVertical: 10, width: 300, }} placeholderTextColor="black" placeholder="Image" /> </View> <Pressable onPress={handleRegister} style={{ width: 200, backgroundColor: "#4A55A2", padding: 15, marginTop: 50, marginLeft: "auto", marginRight: "auto", borderRadius: 6, }} > <Text style={{ color: "white", fontSize: 16, fontWeight: "bold", textAlign: "center", }} > Register </Text> </Pressable> <Pressable onPress={() => navigation.goBack()} style={{ marginTop: 15 }} > <Text style={{ textAlign: "center", color: "gray", fontSize: 16 }}> Already Have an account? Sign in </Text> </Pressable> </View> </KeyboardAvoidingView> </View> ); }; export default RegisterScreen; const styles = StyleSheet.create({});
解决方案
1. 修正React Native的API访问地址
React Native中localhost指向模拟器/真机自身,而非开发电脑,需按场景替换:
- iOS模拟器:可继续用
localhost,或替换为电脑局域网IP - Android模拟器:替换为
http://10.0.2.2:8000(Android模拟器指向宿主电脑的专用IP) - 真机测试:确保手机与电脑同局域网,替换为电脑的局域网IP(如
http://192.168.1.100:8000)
2. 验证后端服务状态
- 确认后端终端输出
Server is running和Success(MongoDB连接成功) - 用Postman直接发送POST请求到
http://localhost:8000/register,测试接口是否正常响应,排除前端逻辑问题
3. 完善MongoDB连接配置
当前连接字符串未指定数据库名称,补充后可避免默认数据库问题:
mongoose.connect( "mongodb+srv://<user>:<password>@cluster0.03lvgad.mongodb.net/your-db-name", { useNewUrlParser: true, useUnifiedTopology: true, } ).catch(err => console.log("MongoDB连接失败", err));
4. 检查User模型定义
确保./models/user.js的字段与前端传入数据匹配,无必填项遗漏:
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, image: String }); module.exports = mongoose.model('User', userSchema);
5. 调试Axios错误详情
修改前端catch块,打印完整错误信息定位问题:
.catch((error) => { Alert.alert( "Registration Error", error.response?.data?.message || error.message || "Unknown error" ); console.log("registration failed", error); });
内容的提问来源于stack exchange,提问作者Sidhartha S
相关产品推荐
相关产品推荐

