iam trying to connect my flutter app to a node server the flutter application has a registration screen that accepts username,password and email from users and it should be reflected to mongodb using the node server im getting this error
here’s my server code
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}`);
});
here’s my flutter code
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
}
}
i spammed gemini and chatgpt but i met an dead end because it says the code looks good they are telling me to turn of the firewall and check network configuration and stuff
2
Answers
Flutter does not allow you to make requests call to http urls, you will need to set up ngrok proxy to deliver your http server as https.
Your app listens port 80.
Use this to listen your port: 5555.