-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
91 lines (78 loc) · 2.39 KB
/
app.js
File metadata and controls
91 lines (78 loc) · 2.39 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var path = require("path");
const http = require('http');
const compression = require('compression');
// const orderRoutes = require('./api/routes/orders');
const config = require('./config/database');
const port = process.env.PORT || 8080;
app.use(compression());
//Database
mongoose.connect(config.database);
//on connection
mongoose.connection.on('connected', () => {
console.log('connected to local db: ' + config.database);
});
mongoose.connection.on('error', (err) => {
if(err){
console.log('Error is: ' +err);
}
});
app.use(express.static(path.join(__dirname, 'public'), {
maxAge: 86400000,
setHeaders: function(res, path) {
res.setHeader("Expires", new Date(Date.now() + 2592000000*30).toUTCString());
}
}));
//Morgan for testing status
app.use(morgan('dev'));
app.use('/uploads', express.static('uploads', {
maxAge: 86400000,
setHeaders: function(res, path) {
res.setHeader("Expires", new Date(Date.now() + 2592000000*30).toUTCString());
}}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//Allow other single page application(or server) to use our resource
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
if(req.method === 'OPTIONS'){
res.header('Access-Control-Allow-Methods', 'PUT, PATCH, POST, DELETE, GET');
return res.status(200).json({});
}
next();
});
//Routes for handling requests
// app.use('/customers', customerRoutes);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
//Error handling for bad requests
app.use((req, res, next) =>{
const error = new Error('Not Found');
error.status = 404;
next(error);
});
//Error handling for other erros(like db and all)
app.use((error, req, res, next) =>{
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
});
});
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
app.listen(port, ()=>{
console.log('Server started on port: '+port);
});
module.exports = app;