@@ -53,11 +53,42 @@ void main(List<String> args) async {
53
53
final ip = InternetAddress .anyIPv4;
54
54
55
55
// Configure a pipeline that logs requests.
56
- final handler =
57
- Pipeline ().addMiddleware (logRequests ()).addHandler (_router.call);
56
+ final handler = Pipeline ()
57
+ .addMiddleware (logRequests ())
58
+ .addMiddleware (enableCors ())
59
+ .addHandler (_router.call);
58
60
59
61
// For running in containers, we respect the PORT environment variable.
60
62
final port = int .parse (Platform .environment['PORT' ] ?? '8000' );
61
63
final server = await serve (handler, ip, port);
62
64
print ('Server listening on port ${server .port }' );
63
65
}
66
+
67
+ Middleware enableCors () {
68
+ return (Handler handler) {
69
+ return (Request request) async {
70
+ // Handle preflight request (OPTIONS)
71
+ if (request.method == 'OPTIONS' ) {
72
+ return Response .ok (
73
+ '' ,
74
+ headers: {
75
+ 'Access-Control-Allow-Origin' : '*' ,
76
+ 'Access-Control-Allow-Methods' : 'GET, POST, PUT, DELETE, OPTIONS' ,
77
+ 'Access-Control-Allow-Headers' :
78
+ 'Origin, Content-Type, Authorization' ,
79
+ },
80
+ );
81
+ }
82
+
83
+ // Forward request and add CORS headers
84
+ final response = await handler (request);
85
+ return response.change (
86
+ headers: {
87
+ 'Access-Control-Allow-Origin' : '*' ,
88
+ 'Access-Control-Allow-Methods' : 'GET, POST, PUT, DELETE, OPTIONS' ,
89
+ 'Access-Control-Allow-Headers' : 'Origin, Content-Type, Authorization' ,
90
+ },
91
+ );
92
+ };
93
+ };
94
+ }
0 commit comments