简体   繁体   English

带CORS的Delphi XE4 Datasnap

[英]Delphi XE4 Datasnap with CORS

I am developing a datasnap server with REST. 我正在使用REST开发一个datasnap服务器。 When the client trying to use a POST request the browser is trying to execute a OPTIONS request first that my server can't respond. 当客户端尝试使用POST请求时,浏览器首先尝试执行OPTIONS请求,我的服务器无法响应。 Searching I found that is a browser security issue named CORS (Cross Origin Resource Sharing) because my client is in a different domain than the datasnap server. 搜索我发现这是一个名为CORS(跨源资源共享)的浏览器安全问题,因为我的客户端与datasnap服务器位于不同的域中。

What should I do, since data snap does not has a OPTIONS rest request ?? 我该怎么办,因为数据快照没有OPTIONS休息请求?

You can set your Datasnap Server to answer to any CORS request on the WebModule BeforeDispatch event. 您可以将Datasnap Server设置为应答WebModule BeforeDispatch事件上的任何CORS请求。

procedure TWebModule1.WebModuleBeforeDispatch(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
  Response.SetCustomHeader('Access-Control-Allow-Origin','*');        

  if Trim(Request.GetFieldByName('Access-Control-Request-Headers')) <> '' then 
  begin 
    Response.SetCustomHeader('Access-Control-Allow-Headers', Request.GetFieldByName('Access-Control-Request-Headers'));        
    Handled := True;
  end;

  if FServerFunctionInvokerAction <> nil then
    FServerFunctionInvokerAction.Enabled := AllowServerFunctionInvoker;
end;

Workaround: use a reverse proxy server for HTTP (Apache HTTP), and configure Apache so that the OPTIONS request will be answered by a different HTTP server. 解决方法:使用HTTP的反向代理服务器(Apache HTTP),并配置Apache,以便OPTIONS请求将由不同的HTTP服务器应答。 From the outside, the client will not be able to see a difference because all communication is done between client and Apache. 从外部来看,客户端将无法看到差异,因为所有通信都是在客户端和Apache之间完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM