-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.js
45 lines (36 loc) · 1000 Bytes
/
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
const express = require("express");
const cors=require('cors');
const dotenv=require('dotenv').config();
const HttpError=require('./Model/HttpError');
const app = express();
const mongoose=require('mongoose');
//cors
app.use(cors());
// Instead of using body-parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
//db connection
mongoose.connect(process.env.DB_URI)
const db=mongoose.connection;
db.on('open',()=>{
console.log('database connected');
})
db.on('error',()=>{
console.log('error while connecting database');
})
//api routes
const route=require('./Routes/userRoutes');
app.use("/api",route);
//handling wrong requests
app.use((req,res,next)=>{
var error=new HttpError('not found',404);
next(error);
})
//response with error message and code
app.use((error,req,res,next)=>{
return res.status(error.code).json({message:error.message});
})
//port listing on 3000
app.listen(process.env.PORT || 3000,()=>{
console.log("listing")
});