-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
79 lines (67 loc) · 2.33 KB
/
server.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const multer = require('multer');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Serve static files from the uploads directory
app.use('/uploads', express.static('uploads'));
// Set up storage for image uploads
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
// MongoDB setup
mongoose.connect('mongodb://localhost:27017/license-plate-db', { useNewUrlParser: true, useUnifiedTopology: true });
// Schema and model
const Schema = mongoose.Schema;
const plateSchema = new Schema({
licensePlate: String,
state: String,
bumperSticker: String,
image: String // Store the path to the image in MongoDB
});
const Plate = mongoose.model('Plate', plateSchema);
// Serve static files (not necessary if you already have this)
app.use(express.static('public'));
// Routes
app.post('/submit', upload.single('image'), async (req, res) => {
const { licensePlate, state, bumperSticker } = req.body;
const image = req.file ? '/uploads/' + req.file.filename : '';
// Check if a document with the same licensePlate and state already exists
let existingPlate = await Plate.findOne({ licensePlate, state });
if (existingPlate) {
// Update existing document
existingPlate.bumperSticker = bumperSticker;
existingPlate.image = image;
await existingPlate.save();
res.send('Information updated successfully!');
} else {
// Create new document
const newPlate = new Plate({ licensePlate, state, bumperSticker, image });
await newPlate.save();
res.send('Information submitted successfully!');
}
});
app.get('/lookup/:licensePlate/:state', async (req, res) => {
const { licensePlate, state } = req.params;
const plate = await Plate.findOne({ licensePlate, state });
if (plate) {
res.json(plate);
} else {
res.json(null); // Return null if not found
}
});
// Start server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});