복붙노트

[SPRING] 스프링 어플리케이션에 각도를 삽입하여 서빙을 실행할 때 스프링 컨트롤러에 액세스

SPRING

스프링 어플리케이션에 각도를 삽입하여 서빙을 실행할 때 스프링 컨트롤러에 액세스

나는 Spring-Angular 응용 프로그램을 설정할 계획입니다. 환경을 설정하는 방법을 테스트하기 위해 Hello World 예제를 시작했습니다. 내가 결국 한 일 :

이 애플리케이션 내에서 Spring-Project 생성 및 Angular-application 생성하기. 이제 HttpClient Angular Module을 통해 Spring-REST-Controllers에 액세스 할 수 있습니다. (코드 예제는 아래 참조).

이점 : mvn 패키지를 사용하여 Angular- 및 Spring- 파트를 하나의 jar로 압축하고 간단히 그것을 tomcat에 배치 할 수 있습니다. 안타깝게도, 서비스를 실행하면 프론트 엔드 만 실행되고 백엔드의 데이터에 액세스 할 수 없습니다. 내 프로젝트 환경을 설정하여 단일 프로젝트 솔루션의 이점을 누리고 여전히 테스트 서비스를 제공 할 수있는 방법이 있습니까?

내가 시도한 것 :

항아리를 포장하고 터미널 (java -jar % jar-file %)을 통해 실행하고 localhost : 8080 / hello를 간단한 / hello 대신 HttpClient의 경로로 사용하십시오. 그것은 슬프게도 효과가 없었습니다.

내가 지금까지 얻은 코드 :

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'HelloWorld';
  message: string;

  constructor(private http : HttpClient) {}

  ngOnInit() : void {
    //this is where I tried to use localhost:8080/hello instead
    this.http.get('/hello').subscribe( data => {
      console.log('DATA', data);
      this.message = data['message'];
    });
  }
}

나머지 컨트롤러 :

package com.example.helloWorld.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class HelloWorldController {

    @GetMapping("/hello")
    public String sayHello() {
        return "{\"message\": \"Hello, World!\"}";
    }

}

Pom.hml http : //maven.apache.org/hsd/maven-4.0.0.hsd ">     4.0.0

<groupId>com.example</groupId>
<artifactId>helloWorld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>helloWorld</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <scope>test</scope>
    </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-autoconfigure</artifactId>
  <version>2.1.0.RELEASE</version>
  <type>jar</type>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
</dependencies>

<build>
    <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <phase>validate</phase>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <executable>ng</executable>
                            <workingDirectory>src/main/ui</workingDirectory>
                            <arguments>
                                <argument>build</argument>
                            </arguments>
                        </configuration>
                    </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

해결법

  1. ==============================

    1.이렇게하려면

    이렇게하려면

    this.http.get('/hello').subscribe( data => {
          console.log('DATA', data);
          this.message = data['message'];
        });
    

    프록시 구성을해야합니다. package.json이있는 디렉토리에 프로젝트 내의 proxy-config.json 파일 하나를 만듭니다.

    {
        "/": {
            "target": "http://localhost:8080",
            "secure": false
        }
    }
    

    스크립트 안의 package.json에서 "start"명령으로 "start"명령을 업데이트하십시오 : "ng serve --proxy-config proxy-config.json", 그런 다음 npm start 명령을 사용하여 프로젝트를 실행하십시오.

  2. from https://stackoverflow.com/questions/53372609/embed-angular-into-spring-application-and-access-spring-controllers-when-running by cc-by-sa and MIT license