1
- import express , { Request , Response } from 'express' ;
2
-
3
- const app = express ( ) ;
4
- const port = process . env . PORT || 3000 ;
5
-
6
- // Middleware to parse JSON bodies
7
- app . use ( express . json ( ) ) ;
8
-
9
- // Simple GET endpoint
10
- app . get ( '/' , ( req : Request , res : Response ) => {
11
- res . send ( 'Hello, world!' ) ;
12
- } ) ;
13
-
14
- // Simple POST endpoint
15
- app . post ( '/data' , ( req : Request , res : Response ) => {
16
- const data = req . body ;
17
- console . log ( data ) ;
18
- res . json ( { received : data } ) ;
19
- } ) ;
20
-
21
- // Start the server
22
- app . listen ( port , ( ) => {
23
- console . log ( `Server is running on port ${ port } ` ) ;
24
- } ) ;
1
+ import fastifyStatic from '@fastify/static'
2
+ import Fastify , { FastifyInstance , FastifyReply , FastifyRequest } from 'fastify'
3
+ import path from 'path'
4
+
5
+ const fastify = Fastify ( {
6
+ logger : true
7
+ } )
8
+
9
+ const publicPath = path . join ( __dirname , 'public' )
10
+ console . log ( 'publicPath' , publicPath )
11
+
12
+ // Register the fastify-static plugin
13
+ fastify . register ( fastifyStatic , {
14
+ root : publicPath ,
15
+ prefix : '/public' ,
16
+ } )
17
+
18
+ // Register CORS plugin
19
+ fastify . register ( require ( '@fastify/cors' ) , {
20
+ origin : '*' , // Allow all origins
21
+ } )
22
+ const routes = ( fastify : FastifyInstance , _ : any , done : ( ) => void ) => {
23
+
24
+ // JSON data
25
+ fastify . post ( '/api' , ( request : FastifyRequest , reply : FastifyReply ) => {
26
+ console . log ( `************ API post request received: ${ JSON . stringify ( request . body ) } ` )
27
+ const data = request . body
28
+ reply . code ( 200 ) . send ( { received : data } )
29
+ } ) ;
30
+
31
+ // root
32
+ fastify . get ( '/' , ( _ : FastifyRequest , reply : FastifyReply ) => {
33
+ console . log ( `************ ROOT post request received` )
34
+ reply . sendFile ( 'index.html' )
35
+ } ) ;
36
+
37
+ done ( ) ;
38
+ }
39
+
40
+ fastify . register ( routes ) ;
41
+
42
+ /**
43
+ * Run the server!
44
+ */
45
+ const start = async ( ) => {
46
+ try {
47
+ await fastify . listen ( { port : 3000 , host : '0.0.0.0' } )
48
+ console . log ( `server listening on 3000` )
49
+ } catch ( err ) {
50
+ fastify . log . error ( err )
51
+ process . exit ( 1 )
52
+ }
53
+ }
54
+ start ( )
0 commit comments