Recent

Author Topic: Request trocando 'GET' por 'OPTIONS'  (Read 3789 times)

automacaosamos

  • New Member
  • *
  • Posts: 21
Request trocando 'GET' por 'OPTIONS'
« on: November 20, 2021, 01:05:27 am »
Olá
Fiz essa pequena API pra responder uma requisições HTTP.
no POSTMAN funciona perfeitamente, mas quando uso o javascript e troca o 'GET' por 'OPTIONS'
Acredito que devo tratar o OPTIONS quando a requisição é AJAX mas não sei como fazer isso,
se alguém puder ajudar.

Iniciante Lazarus

Code: Pascal  [Select][+][-]
  1. program apiteste;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. uses
  6.   {$IFDEF UNIX}{$IFDEF UseCThreads}
  7.   cthreads,
  8.   {$ENDIF}{$ENDIF}
  9.   SysUtils,
  10.   Classes,
  11.   fphttpapp,
  12.   httpdefs,
  13.   httproute,
  14.   fpjson,
  15.   jsonparser;
  16. function DecodeUrl(url: string): string;
  17. var
  18.   x   : integer;
  19.   ch  : string;
  20.   sVal: string;
  21.   Buff: string;
  22. begin
  23.   //Init
  24.   Buff := '';
  25.   x    := 1;
  26.   while x <= Length(url) do
  27.     begin
  28.       ch := url[x];
  29.       if ch = '+' then
  30.         Buff := Buff + ' '
  31.       else
  32.         if ch <> '%' then
  33.           Buff := Buff + ch
  34.         else
  35.           begin
  36.             sVal := Copy(url, x + 1, 2);
  37.             Buff := Buff + char(StrToInt('$' + sVal));
  38.             Inc(x, 2);
  39.           end;
  40.       Inc(x);
  41.     end;
  42.   Result := Buff;
  43. end;
  44.  
  45. procedure JSONResponse(var res: TResponse; data: String);
  46. begin
  47.   res.Content       := data;
  48.   res.Code          := 200;
  49.   res.SetFieldByName('Access-Control-Allow-Origin', '*');
  50.   res.SetFieldByName('Access-Control-Allow-Methods','GET, POST, OPTIONS, PUT, PATCH, DELETE');
  51.   res.SetFieldByName('Access-Control-Allow-Headers','*');
  52.   res.ContentType   := 'application/json';
  53.   res.ContentLength := length(res.Content);
  54.   res.SendContent;
  55. end;
  56.  
  57. procedure TimeEndPoint(req: TRequest; res: TResponse);
  58. var
  59.   JSONObject : TJSONObject;
  60. begin
  61.   JSONObject := TJSONObject.Create;
  62.   try
  63.     JSONObject.Strings['time'] := 'Servidor OK ' + TimeToStr(Time) + req.URI;
  64.     jsonResponse(res, JSONObject.AsJSON);
  65.   finally
  66.     JSONObject.Free;
  67.   end;
  68. end;
  69.  
  70. procedure ApiEndpoint(req: TRequest; res: TResponse);
  71. var
  72.   JSONObject    : TJSONObject;
  73.   Rota          : String;
  74.   Metodo        : String;
  75.   Uri           : String;
  76. begin
  77.   req.RouteParams[''];
  78.   Metodo     := req.Method;  // Aqui estou recebendo OPTIONS quando chamo pelo navegador
  79.   Rota       := req.RouteParams['name'];
  80.   Uri        := DecodeURL(req.URI);
  81.   JSONObject := TJSONObject.Create;
  82.   try
  83.   if Metodo = 'GET' then
  84.     JSONObject.Strings['get'] := 'OK -> ' + Rota
  85.   else
  86.     if Metodo = 'POST' then
  87.       JSONObject.Strings['post'] := 'OK -> ' + Rota
  88.     else
  89.       if Metodo = 'PUT' then
  90.          JSONObject.Strings['put'] := 'OK -> ' + Rota
  91.       else
  92.         if Metodo = 'DELETE' then
  93.            JSONObject.Strings['delete'] := 'OK -> ' + Rota;
  94.  
  95.     JSONResponse(res, JSONObject.AsJSON);
  96.   finally
  97.     FreeAndNil(JSONObject);
  98.   end;
  99.  
  100. end;
  101. begin
  102.   Application.Port     := 8080;
  103.   HTTPRouter.RegisterRoute('/time'     , @timeEndpoint, true);
  104.   HTTPRouter.RegisterRoute('/api/:name', @apiEndpoint);
  105.   Application.Threaded := true;
  106.   writeln('Servidor Rodando: http://localhost:' + IntToStr(Application.Port) + '/time');
  107.   Application.Initialize;
  108.   Application.Run;
  109. end.                                  
  110.  
  111.  
« Last Edit: November 22, 2021, 10:15:33 pm by automacaosamos »

 

TinyPortal © 2005-2018