1
+ import express , { Application , Request , Response , NextFunction } from 'express' ;
2
+ import cors from 'cors' ;
3
+ import collabRoutes from './routes/collab-routes' ;
4
+
5
+ const app : Application = express ( ) ;
6
+
7
+ app . use ( express . urlencoded ( { extended : true } ) ) ;
8
+ app . use ( express . json ( ) ) ;
9
+ app . use ( cors ( ) ) ; // config cors so that front-end can use
10
+ app . options ( "*" , cors ( ) ) ;
11
+
12
+
13
+ // To handle CORS Errors
14
+ app . use ( ( req , res , next ) => {
15
+ res . header ( "Access-Control-Allow-Origin" , "*" ) ; // "*" -> Allow all links to access
16
+
17
+ res . header (
18
+ "Access-Control-Allow-Headers" ,
19
+ "Origin, X-Requested-With, Content-Type, Accept, Authorization" ,
20
+ ) ;
21
+
22
+ // Browsers usually send this before PUT or POST Requests
23
+ if ( req . method === "OPTIONS" ) {
24
+ res . header ( "Access-Control-Allow-Methods" , "GET, POST, DELETE, PUT, PATCH" ) ;
25
+ return res . status ( 200 ) . json ( { } ) ;
26
+ }
27
+
28
+ // Continue Route Processing
29
+ next ( ) ;
30
+ } ) ;
31
+
32
+
33
+ app . get ( "/" , ( req , res , next ) => {
34
+ console . log ( "Sending Greetings!" ) ;
35
+ res . json ( {
36
+ message : "Hello World from collab-service" ,
37
+ } ) ;
38
+ } ) ;
39
+
40
+ // Handle When No Route Match Is Found
41
+ app . use ( ( req , res , next ) => {
42
+ const error : any = new Error ( "Route Not Found" ) ;
43
+ error . status = 404 ;
44
+ next ( error ) ;
45
+ } ) ;
46
+
47
+ app . use ( ( error , req , res , next ) => {
48
+ res . status ( error . status || 500 ) ;
49
+ res . json ( {
50
+ error : {
51
+ message : error . message ,
52
+ } ,
53
+ } ) ;
54
+ } ) ;
55
+
56
+ app . use ( "/collab" , collabRoutes ) ;
57
+
58
+ export default app ;
0 commit comments