Flutter应用无法连接Node.js服务器,注册数据无法同步至MongoDB
Flutter客户端与Node.js服务器连接失败问题
我正在尝试将Flutter应用连接至Node.js服务器,应用的注册页面可收集用户的用户名、密码和邮箱信息,需通过Node.js服务器将数据同步至MongoDB,但目前出现连接失败问题。
Node.js服务器代码
const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); const port = 5555; // Use body-parser middleware to parse JSON request bodies app.use(bodyParser.json()); // Connect to MongoDB (Replace with your MongoDB connection string) mongoose.connect('mongodb+srv://panchalmeet316:meetrocks@cluster0.vb8df.mongodb.net/INSIGHTIFY?retryWrites=true&w=majority&appName=Cluster0') .then(() => { console.log('Connected to MongoDB'); }) .catch((err) => { console.error('Error connecting to MongoDB:', err.message); }); // Define a Mongoose schema for users const userSchema = new mongoose.Schema({ username: { type: String, required: true }, password: { type: String, required: true }, email: { type: String, required: true, unique: true }, }); // Create a Mongoose model from the schema const User = mongoose.model('User', userSchema); // Define an API endpoint for user registration app.post('/register', async (req, res) => { const { username, password, email } = req.body; // Basic validation (you can expand this as needed) if (!username || !email || !password) { return res.status(400).send('All fields are required'); } try { // Create a new user instance const newUser = new User({ username, password, email }); // Save the user to the database await newUser.save(); res.status(201).send('User registered successfully'); } catch (error) { if (error.code === 11000) { // Duplicate email error res.status(400).send('Email is already registered'); } else { res.status(500).send('Server error'); } } }); // Define an API endpoint for user login app.post('/login', async (req, res) => { const { username, password } = req.body; try { const user = await User.findOne({ username }); if (!user) { return res.status(401).send('Invalid username or password'); } const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return res.status(401).send('Invalid username or password'); } // Generate a session token or JWT // const token = jwt.sign({ userId: user._id }, 'your_secret_key'); // res.status(200).json({ token }); } catch (error) { res.status(500).send('Server error'); } }); // Start the server app.listen(() => { console.log(`Server is running on http://192.168.47.1:${port}`); });
Flutter客户端代码
Future<void> registerUser() async { var userData = { 'username': nameController.text, 'password': passwordController.text, 'email': emailController.text, // Use singular 'email' instead of 'emails' }; var jsonData = jsonEncode(userData); try { var response = await http.post( Uri.parse('http://192.168.0.102:5555/register'), headers: { 'Content-Type': 'application/json', }, body: jsonData, ); if (response.statusCode == 200) { print('User registered successfully'); } else { // Handle other status codes switch (response.statusCode) { case 400: print('Registration failed: Bad request (invalid data)'); break; case 409: print('Registration failed: Email already registered'); break; case 500: print('Registration failed: Internal server error'); break; default: print('Registration failed: Unknown error (code: ${response.statusCode})'); } throw Exception('Registration failed'); // Throw an exception for further handling } } on Exception catch (e) { print('An error occurred: $e'); // Display user-friendly error message in your app UI } }
已尝试的解决措施
- 咨询Gemini和ChatGPT,确认代码逻辑无问题
- 关闭防火墙
- 检查网络配置
问题仍未解决,陷入僵局。
内容的提问来源于stack exchange,提问作者meet panchal
相关产品推荐
相关产品推荐

