如果您使用默认设置(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));
}
}