【问题标题】:Separating jhipster back-end and front-end into two projects?将 jhipster 后端和前端分成两个项目?
【发布时间】:2015-05-15 17:00:02
【问题描述】:

我正在尝试使用基于令牌的身份验证 jhipster。效果很好。

现在,我想在不同的域上运行后端和前端代码。我该怎么做?


这是我尝试过的:

  1. 运行yo jhipster 并选择基于令牌的身份验证选项:

    Welcome to the JHipster Generator
    
    ? (1/13) What is the base name of your application? jhipster
    ? (2/13) What is your default Java package name? com.mycompany.myapp
    ? (3/13) Do you want to use Java 8? Yes (use Java 8)
    ? (4/13) Which *type* of authentication would you like to use? Token-based authentication (stateless, with a token)
    ? (5/13) Which *type* of database would you like to use? SQL (H2, MySQL, PostgreSQL)
    ? (6/13) Which *production* database would you like to use? MySQL
    ? (7/13) Which *development* database would you like to use? H2 in-memory with Web console
    ? (8/13) Do you want to use Hibernate 2nd level cache? Yes, with ehcache (local cache, for a single node)
    ? (9/13) Do you want to use clustered HTTP sessions? No
    ? (10/13) Do you want to use WebSockets? No
    ? (11/13) Would you like to use Maven or Gradle for building the backend? Maven (recommended)
    ? (12/13) Would you like to use Grunt or Gulp.js for building the frontend? Grunt (recommended)
    ? (13/13) Would you like to use the Compass CSS Authoring Framework? No
    
    ...
    
    I'm all done. Running bower install & npm install for you
    ^C
    
  2. 将项目复制为jhipster/backendjhipster/frontend

  3. 从后端和前端删除不必要的文件

    rm -rf backend/.bowerrc
    rm -rf backend/.jshintrc
    rm -rf backend/bower.json
    rm -rf backend/Gruntfile.js
    rm -rf backend/package.json
    rm -rf backend/src/main/webapp
    rm -rf backend/src/test/javascript
    
    rm -rf frontend/pom.xml
    rm -rf frontend/src/main/java
    rm -rf frontend/src/main/resources
    rm -rf frontend/src/test/gatling
    rm -rf frontend/src/test/java
    rm -rf frontend/src/test/resources
    
  4. 更改代码以完全消除后端/前端依赖性

    • frontend/Gruntfile.js

      ...
      var parseVersionFromPomXml = function() {
          return '1.2.2.RELEASE';
      };
      ...
      browserSync: { ..., proxy: "localhost:8081" }
      
    • frontend/src/main/webapp/scripts/app/app.js

      angular.module('jhipsterApp', [...])
      .constant('API_URL', 'http://localhost:8080/')
      .run( ... )
      
    • frontend/src/main/webapp/scripts/**/*.service.js

      angular.module('jhipsterApp').factory(..., API_URL) {
          return $http.post(API_URL + 'api/authenticate', ...);
      }
      
      angular.module('jhipsterApp').factory('Account', function Account($resource, API_URL) {
          return $resource(API_URL + 'api/account', {}, {...});
      }
      
      // Make similar changes in all service files.
      
    • backend/pom.xml

      删除 yeoman-maven-plugin

    • backend/src/main/java/com/mycompany/myapp/SimpleCORSFilter.java

      // Copied from here: https://spring.io/guides/gs/rest-service-cors/
      
      @Component
      public class SimpleCORSFilter implements Filter {
          public void doFilter(...) {
              ...
              response.setHeader("Access-Control-Allow-Origin", "*");
              ...
          }
      }
      
  5. 运行

    • 终端标签 #1:BACKEND

      cd backend
      mvn spring-boot:run
      
      ...
      [INFO] com.mycompany.myapp.Application - Started Application in 11.529 seconds (JVM running for 12.079)
      [INFO] com.mycompany.myapp.Application - Access URLs:
      ----------------------------------------------------------
              Local:          http://127.0.0.1:8080
              External:       http://192.168.56.1:8080
      ----------------------------------------------------------
      
    • 终端标签 #2:前端

      cd frontend/src/main/webapp
      npm install -g http-server
      http-server
      
      Starting up http-server, serving ./ on: http://0.0.0.0:8081
      Hit CTRL-C to stop the server
      
    • 终端标签 #3:咕噜声

      cd frontend
      bower install
      npm install
      grunt serve
      
      ...
      [BS] Proxying: http://localhost:8081
      [BS] Access URLs:
       -------------------------------------
             Local: http://localhost:3000
          External: http://10.34.16.128:3000
       -------------------------------------
                UI: http://localhost:3001
       UI External: http://10.34.16.128:3001
       -------------------------------------
      
  6. 浏览http://localhost:3000/#/login

    输入username:passwordadmin:admin

    我们的 BACKEND 标签显示:

    [DEBUG] com.mycompany.myapp.security.Http401UnauthorizedEntryPoint - Pre-authenticated entry point called. Rejecting access
    

显然,我做错了什么。这是什么?

【问题讨论】:

  • 只是一个想法,但也许您可以仔细检查后端是否能够处理有效凭据。见stackoverflow.com/questions/28269487/…
  • 你有没有设法让它运行?
  • @Daniel 不幸的是,没有。在我提出这个问题后,我很快就停止玩 jhipster 了。
  • @musa 我下面的回答帮助了其他一些人,也是我解决问题的方法。请查看并考虑将其标记为已接受的答案。

标签: java angularjs authentication jwt jhipster


【解决方案1】:

当请求因 CORS 失败时,后端没有可见的错误。 HTTP 请求实际上成功了,但是在前端被 javascript 阻止了。 JS 控制台中会出现类似这样的消息。

XMLHttpRequest cannot load http://localhost:8080/api/authenticate. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

您看到的错误消息实际上与身份验证有关。当您启用 CORS 时,您的 JS 将使用 HTTP OPTIONS 方法发送“飞行前”请求。 JHipster 未配置为全局允许 OPTIONS 方法。在做同样的事情时,我自己也遇到了同样的问题。修复非常简单:只需将此行添加到您的 com.mycompany.config.SecurityConfiguration 紧挨在第一个 antMatchers 条目之前(之前)。

.antMatchers(org.springframework.http.HttpMethod.OPTIONS, "/api/**").permitAll()

这将明确允许使用 OPTIONS 方法的所有请求。 CORS 中使用 OPTIONS 方法作为读取所有标头并查看 CORS 请求中允许使用哪些 HTTP 方法的一种方式。

最后,在您的 SimpleCORSFilter 类中,您还应该添加这些标题:

response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "86400"); // 24 Hours
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-auth-token");

【讨论】:

    【解决方案2】:

    在 JHipster 应用程序中分离前端和后端非常简单。如果您想使用 JHipster 单独设置前端和后端应用程序,请按照以下步骤操作:

    1. 为前端和后端应用程序创建两个目录

      • mkdir 前端
      • mkdir 后端
    2. 将您的目录更改为前端并运行 JHipster 命令以创建前端模块

      • cd 前端
      • jhipster --skip-server --db=sql --auth=jwt
      • 如果一切正常,运行 npm start 命令来运行您的前端应用程序。

      我将 mysql 用于 db,将 JWT 用于 auth,如果您想使用 websockets,请添加:“--websocket=spring-websocket”

    3. 现在,将您的目录更改为后端并运行 JHipster 命令来创建后端模块

      • cd .. //因为我们目前正在处理后端目录
      • cd 后端
      • jhipster --skip-client
      • 在运行 Spring Boot 应用程序时运行后端应用程序

    现在,您的前端和后端应用程序分别单独运行,前端通过 REST API 调用与后端应用程序协调。

    【讨论】:

    • 现在你想在 Prod 上部署它,你将创建一个单独的 war/jar 来部署。您必须在项目中更改哪些所有文件?
    • 对于部署,更好的方法是分别部署前端和后端。后端在tomcat上,前端在apache上。
    • 谢谢。但我想部署在 Google App Engine 上。那我应该为它做两个不同的项目吗?
    • 如何将前端应用程序与后端应用程序连接起来(是的,我可以使用休息调用,但是...)?,我得到 SERVER_API_URL:''
    【解决方案3】:

    除了上面 xeorem 的回答,我还必须修改 parse-links-service.js 来处理预检 OPTIONS 响应,它没有“链接”响应头:

    var links = {};
    if (!angular.isObject()) {
        // CORS OPTIONS responses
        return links;
    }
    
    if (header.length == 0) {
        throw new Error("input must not be of zero length");
    }
    
    // Split parts by comma
    var parts = header.split(','); 
    
    ...
    

    不要将 API_URL 添加到 app.js,而是修改 Gruntfile.js 并将 API_URL 添加到 DEV 和 PROD 环境的 ngConstants 块。

    【讨论】:

      【解决方案4】:

      您可以使用 Tomcat 中的 CORS 过滤器。将Tomcat依赖放在pom.xml:

         <dependency>
              <groupId>org.apache.tomcat</groupId>
              <artifactId>tomcat-catalina</artifactId>
              <version>8.0.15</version>
              <scope>provided</scope>
          </dependency>
      

      使用您使用的任何版本的 Tomcat。

      WebConfigurer中添加CORS过滤器初始化:

      private void initCorsFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {
              log.debug("Registering CORS Filter");
              FilterRegistration.Dynamic corsFilter = servletContext.addFilter("corsFilter", new CorsFilter());
              Map<String, String> parameters = new HashMap<>();
              parameters.put("cors.allowed.headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
              parameters.put("cors.allowed.methods", "GET,POST,HEAD,OPTIONS,PUT,DELETE");
              corsFilter.setInitParameters(parameters);
              corsFilter.addMappingForUrlPatterns(disps, false, "/*");
              corsFilter.setAsyncSupported(true);
          }
      

      将此行放在WebConfigurer.onStartup(...)中,尽可能靠近顶部。

      ...
      initCorsFilter(servletContext, disps);
      ...
      

      【讨论】:

        【解决方案5】:

        我使用的是 Jhipster 4.14.5 版

        • 我已将以下文件复制到 project-forntend 文件夹:

          .bowerrc
          吞咽
          pom.xml
          纱线锁
          gulpfile.js
          自述文件.md

          凉亭组件
          .gitattributes
          src/main/web

          bower.json
          .gitignore
          package.json
          目标/www

        • 然后跑:

          纱线安装

          凉亭安装

          一饮而尽

        • 然后将gulp/config.js文件改为:

          api端口:8081

          uri:'http://localhost:'

        • 然后通过运行启动项目:

          一饮而尽

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多