ruscomap/server.js

57 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-02-16 22:01:36 +01:00
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
app.use(bodyParser.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/userDB', { useNewUrlParser: true, useUnifiedTopology: true });
// Create a user schema
const userSchema = new mongoose.Schema({
username: String,
password: String
});
const User = mongoose.model('User', userSchema);
// Handle user registration
app.post('/register', (req, res) => {
const { username, password } = req.body;
const newUser = new User({
username: username,
password: password
});
newUser.save((err) => {
if (err) {
res.status(500).send('Error registering new user');
} else {
res.status(200).send('User registered successfully');
}
});
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
// Handle user authentication
app.post('/login', (req, res) => {
const { username, password } = req.body;
User.findOne({ username: username, password: password }, (err, foundUser) => {
if (err) {
res.status(500).send('Error authenticating user');
} else {
if (foundUser) {
res.status(200).send('User authenticated successfully');
} else {
res.status(401).send('Invalid username or password');
}
}
});
});