-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (45 loc) · 1.45 KB
/
server.js
File metadata and controls
55 lines (45 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import multer from 'multer';
import path from 'path';
import Profile from './models/Profile.js';
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());
// Serve static images from /uploads
app.use('/uploads', express.static('uploads'));
// Multer storage setup
const storage = multer.diskStorage({
destination: 'uploads/',
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
},
});
const upload = multer({ storage });
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
// Get all profiles
app.get('/profiles', async (req, res) => {
const profiles = await Profile.find();
res.json(profiles);
});
// Create a new profile with optional image
app.post('/profiles', upload.single('image'), async (req, res) => {
try {
const profileData = {
...req.body,
image: req.file?.filename || '', // Store only the filename
};
const newProfile = new Profile(profileData);
await newProfile.save();
res.json(newProfile);
} catch (error) {
console.error('Error creating profile:', error);
res.status(500).json({ error: 'Something went wrong.' });
}
});
app.listen(5000, () => console.log('Server running on http://localhost:5000'));