[Previous][Up][Next] Reference for unit 'HTTPDefs' (#fcl)

CORS Support Usage

Cross-Origin Resource Sharing (CORS) allows web applications running at one origin to access resources from another origin. The TCORSSupport class handles CORS headers and validation.

CORS support includes configuration of allowed origins, methods, and headers, as well as handling preflight OPTIONS requests. The HandleRequest method processes CORS requests and returns True if the request should continue or False if it should be blocked.

program CORSExample;

{$mode objfpc}{$H+}

uses
  httpdefs, SysUtils;

procedure HandleCORSRequest(Request: TRequest; Response: TResponse);
var
  CORS: TCORSSupport;
  ContinueProcessing: Boolean;
begin
  CORS := TCORSSupport.Create;
  try
    // Configure CORS settings
    CORS.Enabled := True;
    CORS.AllowedOrigins := 'https://example.com,https://app.example.com';
    CORS.AllowedMethods := 'GET,POST,PUT,DELETE,OPTIONS';
    CORS.AllowedHeaders := 'Content-Type,Authorization,X-Requested-With';
    CORS.MaxAge := 3600; // Cache preflight response for 1 hour

    // Handle the CORS request
    ContinueProcessing := CORS.HandleRequest(Request, Response, []);

    if ContinueProcessing then
    begin
      // Process the actual request
      if Request.Method = 'GET' then
      begin
        Response.Content := '{"message": "CORS request handled successfully"}';
        Response.ContentType := 'application/json';
      end
      else if Request.Method = 'OPTIONS' then
      begin
        // Preflight request - CORS headers already set
        Response.Code := 204; // No Content
      end;

      Writeln('CORS request from origin: ', Request.GetCustomHeader('Origin'));
      Writeln('Request processed successfully');
    end
    else
    begin
      // CORS validation failed
      Response.Code := 403; // Forbidden
      Response.Content := 'CORS policy violation';
      Writeln('CORS request blocked');
    end;
  finally
    CORS.Free;
  end;
end;

var
  Request: TRequest;
  Response: TResponse;
begin
  Request := TRequest.Create;
  Response := TResponse.Create(Request);
  try
    // Simulate a CORS request
    Request.Method := 'GET';
    Request.SetCustomHeader('Origin', 'https://example.com');

    HandleCORSRequest(Request, Response);

    Writeln('Response code: ', Response.Code);
    Writeln('Response content: ', Response.Content);
  finally
    Response.Free;
    Request.Free;
  end;
end.

Documentation generated on: Jan 27 2026