Created
November 27, 2020 15:41
-
-
Save graphicbeacon/e9186517767f7a86c9d24e79a09b8c3a to your computer and use it in GitHub Desktop.
Shelf_router server example with CORS enabled
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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