cors function

Middleware cors({
  1. List<String> origins = const ['*'],
  2. List<String> methods = const ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  3. List<String> headers = const ['Content-Type', 'Authorization'],
})

CORS middleware

Implementation

Middleware cors({
  List<String> origins = const ['*'],
  List<String> methods = const ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  List<String> headers = const ['Content-Type', 'Authorization'],
}) {
  return (Handler innerHandler) {
    return (Request request) async {
      final origin = request.headers['origin'] ?? '*';
      final allowedOrigin = origins.contains('*') ? '*' : (origins.contains(origin) ? origin : null);

      if (request.method == 'OPTIONS') {
        return Response.ok('', headers: {
          'Access-Control-Allow-Origin': allowedOrigin ?? '',
          'Access-Control-Allow-Methods': methods.join(', '),
          'Access-Control-Allow-Headers': headers.join(', '),
        });
      }

      final response = await innerHandler(request);
      return response.change(headers: {
        ...response.headers,
        if (allowedOrigin != null) 'Access-Control-Allow-Origin': allowedOrigin,
      });
    };
  };
}