-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
66 lines (54 loc) · 1.81 KB
/
app.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
const fs = require('fs');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const placesRoutes = require('./routes/places-routes');
const usersRoutes = require('./routes/users-routes');
const HttpError = require('./models/http-error');
const { urlConfig } = require('./util/mongo-connection');
const app = express();
app.use(bodyParser.json());
//middleware to control access to file sistem
app.use('/uploads/images', express.static(__dirname + '/uploads/images'));
//middleware to handle CORS errors
app.use(cors());
// app.use((req, res, next) => {
// res.setHeader('Access-Control-Allow-Origin', '*');
// res.setHeader(
// 'Access-Control-Allow-Headers',
// 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
// );
// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
// next();
// });
app.use('/api/places', placesRoutes);
app.use('/api/users', usersRoutes);
app.use((req, res, next) => {
const error = new HttpError('Could not find this route.', 404);
throw error;
});
app.use((error, req, res, next) => {
if (req.file) {
fs.unlink(req.file.path, (err) => {
console.log(err);
});
}
if (res.headerSent) {
return next(error);
}
res.status(error.code || 500);
res.json({ message: error.message || 'Unknown Error.' });
});
mongoose
.connect(
// `mongodb+srv://${urlConfig}@cluster0.mz5rb.mongodb.net/mern?retryWrites=true&w=majority` //use mongo-connection
`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.mz5rb.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority` //use env variables
)
.then(() => {
app.listen(5000);
})
.catch((err) => {
console.log(err);
});