Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shelf_router server example with CORS enabled
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
void start() async {
// Initiate server
const port = 8081;
final app = Router();
// CORS Settings
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, Content-Type',
};
app.get('/', (Request request) async {
return Response.ok(
'Hello World',
headers: {
'Content-Type': 'application/json',
...corsHeaders, // add corsHeaders to response headers of each route
},
);
});
// Set CORS headers with every request
final handler = Pipeline().addMiddleware((innerHandler) {
return (request) async {
final response = await innerHandler(request);
print(request.headers);
// Set CORS when responding to OPTIONS request
if (request.method == 'OPTIONS') {
return Response.ok('', headers: corsHeaders);
}
// Move onto handler
return response;
};
}).addHandler(app.handler);
await io.serve(handler, 'localhost', port);
print('Server listening on port $port');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment