Recent

Author Topic: CORS/AJAX with fpHTTPap Lazarus  (Read 2780 times)

automacaosamos

  • New Member
  • *
  • Posts: 11
CORS/AJAX with fpHTTPap Lazarus
« on: November 22, 2021, 04:27:45 pm »
Could you help me with an example of an API using:
fphttpapp, httpdefs, httproute, fpjson

that implements CORS to receive AJAX requests ??

thanks

Leledumbo

  • Hero Member
  • *****
  • Posts: 8402
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: CORS/AJAX with fpHTTPap Lazarus
« Reply #1 on: December 07, 2021, 05:49:41 am »
fpjson not required. CORS is implemented as a HTTP OPTIONS handler, so practically just:
Code: Pascal  [Select][+][-]
  1. procedure Whatever(ARequest: TRequest; AResponse: TResponse);
  2. var
  3.   Origin: String;
  4. begin
  5.   if ARequest.Method = 'OPTIONS' then begin // handle CORS request
  6.     // normally, you would check the sent ORIGIN header, to see who sent the request
  7.     Origin := HttpRequest.GetCustomHeader('Origin');
  8.     // for instance, you only allow it from your own domain
  9.     if Origin = 'myowndomain.com' then begin
  10.       // send the header that allows it to request
  11.       AResponse.SetCustomHeader('Access-Control-Allow-Origin', Origin); // or if you allow it from anywhere, use '*' instead of Origin
  12.     end;
  13.   end;
  14. end;
  15.  
  16. begin
  17.    HTTPRouter.RegisterRoute('/', @Whatever);
  18. end.
  19.  

 

TinyPortal © 2005-2018