iam 尝试将我的 flutter 应用程序连接到节点服务器,flutter 应用程序有一个注册屏幕,可以接受用户的用户名、密码和电子邮件,并且应该使用节点服务器将其反映到 mongodb,我收到此错误
这是我的服务器代码
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:[email protected]/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}`);
});
这是我的颤振代码
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 发送了垃圾邮件,但我遇到了死胡同,因为它说代码看起来不错,他们告诉我关闭防火墙并检查网络配置和其他东西
Flutter 不允许您向 http url 发出请求,您需要设置 ngrok 代理以将您的 http 服务器作为 https 提供。