我在将Angular-app与Spring Boot REST后端连接时遇到问题。有什么简单的方法可以使其在一个本地主机端口上一起运行?
答案 0 :(得分: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));
}
}