delphi idhttpserver ajax 跨域解决方法

解决方案

TIdHTTPServer的onCommandGet方法有三个参数,分别是上下文,请求体,响应体。
我们只需要在响应体中加上Access-Control-Allow-OriginAccess-Control-Allow-HeadersAccess-Control-Allow-Method三个配置即可

procedure TMain.idHttpServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; 
    AResponseInfo: TIdHTTPResponseInfo);
begin
    AResponseInfo.CustomHeaders.Add('Access-Control-Allow-Origin:*');
    AResponseInfo.CustomHeaders.Add('Access-Control-Allow-Headers:*');
    AResponseInfo.CustomHeaders.Add('Access-Control-Allow-Method:*');      
    AResponseInfo.ContentType := 'text/HTML;charset=utf-8';
    AResponseInfo.ContentText := AnsiToUtf8('响应数据');
end;

注意:大家比较常用的是onCommandGet方法,但实际上他默认没有调用onCommandGet方法,而是调用了onCommandOther方法。所以我们应该把业务逻辑封装一下,然后分别在get和other事件里调用这个公用方法,当然也可以效仿java servlet中常用的写法,onPost里面直接调用onGet。

参考资料:https://segmentfault.com/a/1190000012469713

原文地址:https://www.cnblogs.com/tc310/p/14312574.html