-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
56 lines (45 loc) · 1.38 KB
/
index.js
File metadata and controls
56 lines (45 loc) · 1.38 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
56
const express = require ('express');
const app = express();
const path = require ('path');
const mongoose = require('mongoose');
const ejsMate = require('ejs-mate');
const methodOverride = require('method-override');
const Trip = require('./models/trip');
const PORT = process.env.PORT || 3000;
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/travelSurvey', {useNewUrlParser: true, useUnifiedTopology: true,})
.then(()=>{
console.log("Connection open")
})
.catch(err=>{
console.log("Connection failed!")
console.log(err)
})
// Middleware
app.engine('ejs',ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(methodOverride('_method'));
// Routescls
app.get('/', async(req, res) => {
res.render('index');
});
app.post('/submit',async(req, res) => {
const {from,to,mode,purpose}= req.body;
// Check if all fields are provided
if (!from || !to || !mode || !purpose) {
return res.status(400).send('All fields are required');
}
const newTrip = new Trip({from,to,mode,purpose});
try{
await newTrip.save();
res.redirect('/')
}catch(err){
console.error(err);
res.status(500).send('Error saving trip.')
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});