|
| 1 | +// ./express-server/app.js |
| 2 | +import express from 'express'; |
| 3 | +import path from 'path'; |
| 4 | +import bodyParser from 'body-parser'; |
| 5 | +import logger from 'morgan'; |
| 6 | +import mongoose from 'mongoose'; |
| 7 | +import SourceMapSupport from 'source-map-support'; |
| 8 | + |
| 9 | +// import routes |
| 10 | +import todoRoutes from './routes/todo.server.route'; |
| 11 | + |
| 12 | +// define our app using express |
| 13 | +const app = express(); |
| 14 | + |
| 15 | +// allow-cors |
| 16 | +app.use(function(req,res,next){ |
| 17 | + res.header("Access-Control-Allow-Origin", "*"); |
| 18 | + res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); |
| 19 | + next(); |
| 20 | +}) |
| 21 | + |
| 22 | + |
| 23 | +// configure app |
| 24 | +app.use(logger('dev')); |
| 25 | +app.use(bodyParser.json()); |
| 26 | +app.use(bodyParser.urlencoded({ extended:true })); |
| 27 | +app.use(express.static(path.join(__dirname, 'public'))); |
| 28 | + |
| 29 | + |
| 30 | +// set the port |
| 31 | +const port = process.env.PORT || 3001; |
| 32 | + |
| 33 | +// connect to database |
| 34 | +mongoose.Promise = global.Promise; |
| 35 | +mongoose.connect('mongodb://localhost/mern-todo-app', { |
| 36 | + useMongoClient: true, |
| 37 | +}); |
| 38 | + |
| 39 | +// add Source Map Support |
| 40 | +SourceMapSupport.install(); |
| 41 | + |
| 42 | +app.use('/api', todoRoutes); |
| 43 | + |
| 44 | +app.get('/', (req,res) => { |
| 45 | + return res.end('Api working'); |
| 46 | +}) |
| 47 | + |
| 48 | +// catch 404 |
| 49 | +app.use((req, res, next) => { |
| 50 | + res.status(404).send('<h2 align=center>Page Not Found!</h2>'); |
| 51 | +}); |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | +// start the server |
| 56 | +app.listen(port,() => { |
| 57 | + console.log(`App Server Listening at ${port}`); |
| 58 | +}); |
0 commit comments