I've a problem with connecting Angular-app with Spring Boot REST backend. Is there any easy way to make it running on one localhost port together?
-
1Please add a description. What problems arise, what errors you get. See the tutorial on how to ask questions. See the How to ask page (stackoverflow.com/help/how-to-ask) for help clarifying this question.Anton Gorbunov– Anton Gorbunov2019-01-25 16:11:50 +00:00Commented Jan 25, 2019 at 16:11
-
check this course udemy.com/angular-4-java-developers/learn/v4/contentAchillesVan– AchillesVan2019-01-25 17:05:35 +00:00Commented Jan 25, 2019 at 17:05
1 Answer
If you run the application with the default settings (Angular CLI: ng serve), the front-end will start on port 4200.
The back-end application will be launched on the port set in the application.yml (or application.properties) file.
Check at what port you run the back-end application:
server:
port: ${PORT:10101}
Next, create a proxy.config.json file (for example, with the package.json file), which reads as follows:
{
"/api/*": {
"target": "http://localhost:10101",
"secure": false,
"logLevel": "debug"
}
}
Then add the package.json file to the script that enables the front-end application entry:
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.config.json",
...
and launching the front-end from the terminal:
npm start
An example of an @Injectable requesting a back-end:
@Injectable()
export class MyService {
constructor(private http: HttpClient) {
}
searchClients(words: string): Observable<ClientDTO[]> {
return this.http.get<ClientDTO[]>('api/client/search?searchWords=' + encodeURIComponent(words));
}
}
And back-end @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));
}
}
