【问题标题】:How to deploy Angular 7 front with Spring Boot backend如何使用 Spring Boot 后端部署 Angular 7 前端
【发布时间】:2019-06-19 11:55:54
【问题描述】:

我在将 Angular-app 与 Spring Boot REST 后端连接时遇到问题。有什么简单的方法可以让它在一个本地主机端口上一起运行?

【问题讨论】:

标签: angular spring-boot angular-cli


【解决方案1】:

如果您使用默认设置(Angular CLI:ng serve)运行应用程序,前端将在端口 4200 上启动。

后端应用程序将在 application.yml(或 application.properties)文件中设置的端口上启动。

检查您在哪个端口运行后端应用程序:

server:
  port: ${PORT:10101}

接下来,创建一个proxy.config.json文件(例如,带有package.json文件),内容如下:

{
  "/api/*": {
    "target": "http://localhost:10101",
    "secure": false,
    "logLevel": "debug"
  }
}

然后将package.json文件添加到启用前端应用入口的脚本中:

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.config.json",
...

并从终端启动前端:

npm 开始

@Injectable 请求后端的示例:

@Injectable()
export class MyService {

  constructor(private http: HttpClient) {
  }

  searchClients(words: string): Observable<ClientDTO[]> {
    return this.http.get<ClientDTO[]>('api/client/search?searchWords=' + encodeURIComponent(words));
  }

}

和后端@RestController:

@RestController
@RequestMapping(path = "api/client")
public class ClientController {

    private final ClientService clientService;

    @Autowired
    public ClientController(ClientService clientService) {
        this.clientService = clientService;
    }

    @GetMapping(path = "search")
    public ResponseEntity<List<ClientDTO>> searchClient(@RequestParam String searchWords) {
        return ResponseEntity.ok(clientService.searchClient(searchWords));
    }

}

【讨论】:

    猜你喜欢
    • 2019-11-17
    • 1970-01-01
    • 2018-12-27
    • 2018-03-15
    • 2022-01-24
    • 2020-11-05
    • 2017-10-22
    • 2017-06-23
    • 1970-01-01
    相关资源
    最近更新 更多