CORS¶
Cross-Origin Resource Sharing (CORS) allows web browsers to make requests to your Trysil HTTP server from a different origin (domain, protocol, or port).
Configuration¶
LServer.CorsConfig.AllowHeaders := 'Content-Type, Authorization';
LServer.CorsConfig.AllowOrigin := '*';
To restrict access to a specific origin:
Configuration Properties¶
| Property | Type | Description |
|---|---|---|
AllowOrigin |
String |
Allowed origin(s). Use '*' for any origin, or a specific URL. |
AllowHeaders |
String |
Comma-separated list of allowed request headers. |
How It Works¶
CORS headers are automatically added to all HTTP responses. The TTHttpCors module handles this transparently:
-
Preflight requests: When a browser sends an
OPTIONSrequest to check CORS policy, Trysil responds automatically with the configured headers. You do not need to defineOPTIONSendpoints in your controllers. -
Regular requests: The
Access-Control-Allow-OriginandAccess-Control-Allow-Headersheaders are added to every response. -
Controller registration: When you register your controllers,
TTHttpCorsinternally registers matching CORS controllers for their URI patterns. This ensures that preflight requests are handled for every endpoint you define.
Typical Setup¶
var LServer := TTHttpServer<TAPIContext>.Create;
try
LServer.BaseUri := 'http://localhost';
LServer.Port := 8080;
// Allow requests from any origin during development
LServer.CorsConfig.AllowOrigin := '*';
LServer.CorsConfig.AllowHeaders := 'Content-Type, Authorization';
LServer.RegisterAuthentication<TMyAuth>();
LServer.RegisterController<TPersonController>();
LServer.Start;
ReadLn;
LServer.Stop;
finally
LServer.Free;
end;
Tip
During development, use '*' for AllowOrigin to avoid CORS issues. In production, restrict it to your application's actual origin for security.