I have started to create a project with Angular 11 and Spring Boot, but I am having problems with the communication via API
. From the Tomcat server it starts from port 8080 in the path ''
. But when creating a new record it shows me the error POST http://localhost:4200/api/client 404 (Not Found)
.
This is my controler.java
:
@RequestMapping("/api/client")
public class ClienteController {
@GetMapping({"/", ""})
public List<Cliente> getAll() throws CMException {
return clienteService.findAll();
}
@PostMapping({"/", ""})
public Cliente create(@RequestBody Cliente cliente) throws CMException {
return clienteService.create(cliente);
}
}
This is my environment.ts
:
export const environment = {
production: false,
baseUrl: '/api'
};
This is my client.service.ts
:
const PREFIX = `${environment.baseUrl}/client`;
@Injectable()
export class ClientService implements IForm<Client> {
constructor(
private http: HttpClient
) {}
public list(filter: any = {}): Observable<Client[]> {
return this.http.get<Client[]>(PREFIX, {params: filter});
}
public create(client: Client): Observable<Client> {
return this.http.post<Client>(PREFIX, client);
}
}
This is my component.ts
:
save() {
if (this.formNew.valid) {
if (this.isNew) {
this.clientService.create(this.formNew.value).subscribe(client => {
console.log(`New client: ${cliente.id}`);
this.back();
}, error => {
console.log(`Error client: ${error}`);
});
}
}
}
I have created the proxy.conf.json
file with the following parameters:
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
My problem: what can go wrong so that when creating the new record the communication between the back and the front does not take place? should I add something else? I'm pretty stuck on this because I can't see the problem
When defining the baseUrl
you have to define it to your API URL which is http://localhost:8080
as what you have currently is nothing in the baseUrl
hence it's set to the angular url you're running on. You will have to set it in your environment.ts
otherwise, the PREFIX
won't point to your API
export const environment = {
production: false,
baseUrl: 'http://localhost:8080'
};