Skip to content
Permalink
cadb4c60c1
Switch branches/tags

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?
Go to file
 
 
Cannot retrieve contributors at this time
57 lines (48 sloc) 1.82 KB
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();
});
//Ensuring a browser that reaches the API's homepage is redirected to an existing route
app.get('/', function(req, res) {
res.redirect('/itemlist');
});
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;