Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
304CEM_resit_backend/app.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
56 lines (47 sloc)
1.75 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
const morgan = require('morgan'); | |
const bodyParser = require('body-parser'); | |
const mongoose = require('mongoose'); | |
const itemRoutes = require('./api/routes/items'); | |
const userRoutes = require('./api/routes/user'); | |
const msgRoutes = require('./api/routes/messages'); | |
//Method to connect the API to an existing MongoDB database | |
mongoose.connect( | |
'mongodb+srv://Caracold:304CEM-resit@cluster0-kbwm8.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true }) | |
//Setting dependencies for parsing and setting the uploads folder to public to allow access to image files. | |
app.use(morgan('dev')); | |
app.use('/uploads', express.static('uploads')); | |
app.use(bodyParser.urlencoded({ extended: false })); | |
app.use(bodyParser.json()); | |
//Middleware setting permissions to avoid browser-related errors | |
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', 'GET, POST, PATCH, DELETE'); | |
return res.status(200).json({}); | |
} | |
next(); | |
}); | |
app.get('/', function(req, res) { | |
res.send('This is the root page') | |
}) | |
app.use('/itemlist', itemRoutes); | |
app.use('/user', userRoutes); | |
app.use('/inbox', msgRoutes); | |
//Catch inexistent routes with a 404 error | |
app.use((req, res, next) => { | |
const error = new Error('Address not found'); | |
error.status = 404; | |
next(error); | |
}) | |
app.use((error, req, res, next) => { | |
res.status(error.status || 500); | |
res.json({ | |
error: { | |
message: error.message | |
} | |
}) | |
}) | |
module.exports = app; |