Project Setup
mkdir node-api && cd node-api
npm init -y
npm install express mongoose dotenv cors helmet morgan
npm install -D nodemon
Project Structure
src/
├── config/
│ └── database.js
├── controllers/
│ └── userController.js
├── middleware/
│ └── auth.js
├── models/
│ └── User.js
├── routes/
│ └── userRoutes.js
└── app.js
Main Application (src/app.js)
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const connectDB = require('./config/database');
require('dotenv').config();
const app = express();
// Connect to MongoDB
connectDB();
// Middleware
app.use(helmet());
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
// Routes
app.use('/api/users', require('./routes/userRoutes'));
// Error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
User Model
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
}, { timestamps: true });
userSchema.pre('save', async function(next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 10);
});
module.exports = mongoose.model('User', userSchema);
User Controller
const User = require('../models/User');
exports.getUsers = async (req, res) => {
const users = await User.find().select('-password');
res.json(users);
};
exports.createUser = async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).json({ id: user._id, name: user.name });
} catch (error) {
res.status(400).json({ error: error.message });
}
};
Run the API
npm run dev
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!