Forum > Portuguese
Request trocando 'GET' por 'OPTIONS'
(1/1)
automacaosamos:
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 [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---program apiteste; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} SysUtils, Classes, fphttpapp, httpdefs, httproute, fpjson, jsonparser;function DecodeUrl(url: string): string;var x : integer; ch : string; sVal: string; Buff: string;begin //Init Buff := ''; x := 1; while x <= Length(url) do begin ch := url[x]; if ch = '+' then Buff := Buff + ' ' else if ch <> '%' then Buff := Buff + ch else begin sVal := Copy(url, x + 1, 2); Buff := Buff + char(StrToInt('$' + sVal)); Inc(x, 2); end; Inc(x); end; Result := Buff;end; procedure JSONResponse(var res: TResponse; data: String);begin res.Content := data; res.Code := 200; res.SetFieldByName('Access-Control-Allow-Origin', '*'); res.SetFieldByName('Access-Control-Allow-Methods','GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.SetFieldByName('Access-Control-Allow-Headers','*'); res.ContentType := 'application/json'; res.ContentLength := length(res.Content); res.SendContent;end; procedure TimeEndPoint(req: TRequest; res: TResponse);var JSONObject : TJSONObject;begin JSONObject := TJSONObject.Create; try JSONObject.Strings['time'] := 'Servidor OK ' + TimeToStr(Time) + req.URI; jsonResponse(res, JSONObject.AsJSON); finally JSONObject.Free; end;end; procedure ApiEndpoint(req: TRequest; res: TResponse);var JSONObject : TJSONObject; Rota : String; Metodo : String; Uri : String;begin req.RouteParams['']; Metodo := req.Method; // Aqui estou recebendo OPTIONS quando chamo pelo navegador Rota := req.RouteParams['name']; Uri := DecodeURL(req.URI); JSONObject := TJSONObject.Create; try if Metodo = 'GET' then JSONObject.Strings['get'] := 'OK -> ' + Rota else if Metodo = 'POST' then JSONObject.Strings['post'] := 'OK -> ' + Rota else if Metodo = 'PUT' then JSONObject.Strings['put'] := 'OK -> ' + Rota else if Metodo = 'DELETE' then JSONObject.Strings['delete'] := 'OK -> ' + Rota; JSONResponse(res, JSONObject.AsJSON); finally FreeAndNil(JSONObject); end; end;begin Application.Port := 8080; HTTPRouter.RegisterRoute('/time' , @timeEndpoint, true); HTTPRouter.RegisterRoute('/api/:name', @apiEndpoint); Application.Threaded := true; writeln('Servidor Rodando: http://localhost:' + IntToStr(Application.Port) + '/time'); Application.Initialize; Application.Run;end.
Navigation
[0] Message Index