在Delphi中配置DMVC Framework的CORS以解决跨域请求问题
问题场景
在本地测试机上使用Delphi 11.2测试TMS WEB Core 2与DMVC 3.2.2:
- 通过向导创建仅添加CORS选项的简易DMVC服务器,服务器可在浏览器正常访问
- 创建包含WebHttpRequest和WebMemo组件的TMS Web Core项目,运行时发送请求出现跨域错误
请求代码:
WebHttpRequest1.URL := 'http://localhost:8080/api/test'; WebHttpRequest1.Execute( procedure(AResponse: string; AReq: TJSXMLHttpRequest) begin WebMemo1.Lines.Add(AResponse); end );
错误提示:
ERROR
HTTP request error @http://localhost:8080/api/test | fMessage::HTTP request error @http://localhost:8080/api/test fHelpContext::0
at http://localhost:8000/Project1/Project1.js [263:50]
浏览器控制台核心报错:
Access to XMLHttpRequest at 'localhost:8080/api/test' from origin 'localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'localhost:8080' that is not equal to the supplied origin.
解决方案:正确配置DMVC的CORS
DMVC 3.2.2内置CORS支持,核心是确保Access-Control-Allow-Origin匹配前端请求的完整Origin(即http://localhost:8000),以下是两种配置方式:
方式1:通过可视化组件属性配置
- 在DMVC服务器项目中找到
TDMVCServer组件 - 开启CORS:将
CORS.Enabled设为True - 设置允许的来源:在
CORS.AllowOrigin中添加http://localhost:8000(允许多个来源用逗号分隔,如http://localhost:8000,http://127.0.0.1:8000) - 可选:根据需求配置
AllowMethods(默认覆盖GET/POST/PUT/DELETE/OPTIONS)、AllowHeaders等参数
方式2:通过代码动态配置
适合需要动态调整CORS规则的场景,在服务器启动前添加如下代码:
uses MVCFramework.CORS; procedure TMainForm.FormCreate(Sender: TObject); var LCORSConfig: TCORSConfig; begin DMVCServer1.Active := False; LCORSConfig := TCORSConfig.Create; try LCORSConfig.Enabled := True; // 添加允许的前端来源 LCORSConfig.AllowOrigin.Add('http://localhost:8000'); // 可添加多个来源 // LCORSConfig.AllowOrigin.Add('http://127.0.0.1:8000'); // 设置允许的请求方法 LCORSConfig.AllowMethods.Add('GET'); LCORSConfig.AllowMethods.Add('POST'); LCORSConfig.AllowMethods.Add('OPTIONS'); // 设置允许的请求头 LCORSConfig.AllowHeaders.Add('Content-Type'); // 将配置应用到服务器 DMVCServer1.SetCORSConfig(LCORSConfig); finally LCORSConfig.Free; end; DMVCServer1.Active := True; end;
关键注意事项
- 必须填写完整的Origin:包含协议(http/https)、域名、端口,不能只写
localhost:8000,必须是http://localhost:8000 - 测试环境可临时用
*允许所有来源,但生产环境禁止此操作,需严格指定可信来源 - DMVC会自动处理OPTIONS预请求,无需额外编写路由逻辑
内容的提问来源于stack exchange,提问作者Dreamer64

