You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VirtualBox中运行的REST端点无法被Flutter应用调用问题求助

问题根因判定

你遇到的是Flutter运行在Web平台的典型CORS(跨域资源共享)错误,浏览器的同源策略会默认阻止不同源的请求,和你后端运行在VirtualBox还是WSL无直接关联。


解决方案

1. 本地调试临时方案(仅开发阶段可用)

不需要修改后端代码,直接启动禁用安全策略的Chrome运行调试即可:

  • Windows端执行命令:flutter run -d chrome --web-browser-flag "--disable-web-security"
  • Mac端先执行命令启动禁用安全策略的Chrome:open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security,再正常运行Flutter Web调试

该方案仅适用于本地开发,不可用于生产环境。

2. 后端配置CORS(全环境通用,推荐)

在Spring Boot服务端配置跨域允许规则即可,有两种常用配置方式:

方式1:单接口/Controller配置

直接给对应接口的Controller类或者方法添加@CrossOrigin注解:

@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS})
@PostMapping("/trusteeman/building/register")
public Object register(/* 你的业务参数 */) {
    // 你的业务逻辑
}

方式2:全局跨域配置

新增配置类统一配置所有接口的跨域规则:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

如果项目集成了Spring Security,需要额外放开OPTIONS预检请求的拦截:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        // 其余你的权限配置逻辑
        ;
}

3. 兜底排查项

如果配置完仍有错误,请依次检查:

  • Spring Boot配置中绑定地址需为0.0.0.0而非127.0.0.1,否则外部设备无法访问,配置项:server.address=0.0.0.0
  • 用Postman或者浏览器直接访问后端接口,确认接口本身可正常响应
  • 生产环境部署时建议用Nginx做反向代理,将前端页面和后端接口统一为同域名同端口,从根源避免跨域问题

内容的提问来源于stack exchange,提问作者user3465651

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 14:27:04