启动iam-service与iam前端应用遇到无法跨域访问的问题

  • Choerodon平台版本:0.8.0

  • 运行环境(如localhost或k8s):localhost

  • 遇到问题时的前置条件:

服务器启动iam-service服务以及必要的7个服务,本机启动choerodon-front-iam

  • 问题描述:

    启动前端应用,登录完成后显示一直在加载中,浏览器检查结果: 在访问服务器中iam服务的资源时返回Invalid CORS request

  • 修改的数据:
    choerodon-front-iam 中的config.js文件: 仅改动了server

   const config = {
    local: true, // 是否为本地开发
  clientId: 'localhost', // 必须填入响应的客户端(本地开发)
  titlename: 'Choerodon', //  项目页面的title名称
  favicon: 'favicon.ico', //  项目页面的icon图片名称
  theme: {
    'primary-color': '#3F51B5',
  },
  cookieServer: '', //  子域名token共享
  server: 'http://192.168.xx.xx:8030',
  dashboard: {
    iam: 'src/app/iam/dashboard/*',
  },
};

module.exports = config;

  • 报错信息(请尽量使用代码块的形式展现):

    Failed to load
    http://192.168.xx.xx:8030/iam/v1/users/self:
    Response to preflight request doesn’t pass access control check:
    No Access-Control-Allow-Origin header is present on the requested resource.
    Origin http://localhost:9090 is therefore not allowed access.

  • 疑问:

    在api-gateway的源码中是有对跨域访问做设置的,但是为什么仍未生效呢?

public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.setMaxAge(18000L);
        config.addAllowedMethod("*");
        //添加response暴露的header
        String[] responseHeader =
                {"date", "content-encoding", "server", "etag", "vary",
                        "content-type", "transfer-encoding", "connection", "x-application-context"};
        config.setExposedHeaders(Arrays.asList(responseHeader));
        source.registerCorsConfiguration("/**", config);

        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

前端server地址配错了,server地址应该是gateway的ip,端口是8080,你这样不经过api-gateway,跨域设置肯定不生效

想了一下,确实是这样的问题。感谢,localhost启动choerodon-front-iam没有问题了。
但是问题再延伸一下,在另一台服务器启动choerodon-front-iam时,浏览器检查出现如下错误:

其中config.js的配置如下:

   const config = {
    local: true, // 是否为本地开发
  clientId: '192.168.xx.xxx', // 必须填入响应的客户端(本地开发)
  titlename: 'Choerodon', //  项目页面的title名称
  favicon: 'favicon.ico', //  项目页面的icon图片名称
  theme: {
    'primary-color': '#3F51B5',
  },
  cookieServer: '', //  子域名token共享
  server: 'http://192.168.xx.xx:8030',
  dashboard: {
    iam: 'src/app/iam/dashboard/*',
  },
};

module.exports = config;

不清楚是不是clientId配置错误

服务器部署我们建议用npm run build来构建代码,然后部署在nginx上,而不是用npm start, 因为start是开发者模式,会显示一些警告错误信息,其中sockjs-node之类的错误是webpack-dev-server报的错,主要作用是监听文件的变化时热构建js代码然后刷新页面用的。

Got it, thanks :slight_smile: