Alright, I'll give you a simple example of how to set up user signup in a MERN (MongoDB, Express.js, React.js, Node.js) stack app. In this example, we'll make an easy registration form on the frontend and manage the registration process on the backend.
Backend (Node.js/Express):
- Update the
server.js
file in thee-commerce-server
directory:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bcrypt = require('bcrypt');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
mongoose.connect('mongodb://localhost:27017/e-commerce', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const userSchema = new mongoose.Schema({
username: String,
password: String,
});
const User = mongoose.model('User', userSchema);
app.post('/api/register', async (req, res) => {
try {
const { username, password } = req.body;
// Check if username already exists
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(400).json({ error: 'Username already taken' });
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Create a new user
const newUser = new User({ username, password: hashedPassword });
await newUser.save();
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This backend code creates an easy registration endpoint (/api/register
). It checks if the username is already in use, secures the password, and saves the new user to the database.
Frontend (React):
- Update the
src/App.js
file in thee-commerce-client
directory:
import React, { useState } from 'react';
const App = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleRegister = () => {
fetch('/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
})
.then((res) => res.json())
.then((data) => alert(data.message))
.catch((error) => console.error('Error registering:', error));
};
return (
<div>
<h1>User Registration</h1>
<label>
Username:
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</label>
<br />
<label>
Password:
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<br />
<button onClick={handleRegister}>Register</button>
</div>
);
};
export default App;
The frontend code has a simple registration form with spaces for a username and password. When the user clicks the "Register" button, their details are sent to the backend (/api/register
).
Be sure to run your MongoDB server and then start both the frontend and backend applications:
# In the e-commerce-server directory
node server.js
# In the e-commerce-client directory
npm start
This is a simple example. In a real-world app, you'd want to add features like password confirmation, form validation, and better error handling. Also, think about using HTTPS in a production setting for secure communication.