Skip to content

Commit 5403d49

Browse files
committed
Enable cors
1 parent 27e6f1a commit 5403d49

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

lib/backend/rest_backend_service.dart

+3-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import 'backend_service.dart';
1010

1111
const String globeBackendUrl =
1212
'https://pluto-server-cn2xut2-birjuvachhani.globeapp.dev/';
13+
const String cloudRunUrl =
14+
'https://pluto-510516922464.asia-south1.run.app';
1315

1416
class RestBackendService extends BackendService {
1517
String baseUrl = '';
@@ -21,7 +23,7 @@ class RestBackendService extends BackendService {
2123
baseUrl = 'http://localhost:8000';
2224
} else {
2325
log('Initializing backend with production server');
24-
baseUrl = globeBackendUrl;
26+
baseUrl = cloudRunUrl;
2527
}
2628
}
2729

server/bin/server.dart

+33-2
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,42 @@ void main(List<String> args) async {
5353
final ip = InternetAddress.anyIPv4;
5454

5555
// 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);
5860

5961
// For running in containers, we respect the PORT environment variable.
6062
final port = int.parse(Platform.environment['PORT'] ?? '8000');
6163
final server = await serve(handler, ip, port);
6264
print('Server listening on port ${server.port}');
6365
}
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

Comments
 (0)