Issue
I've actually crate an angular service to get data from the server which running on 'localhost:8080/' (endpoint /user) . But when I serve the angular project on 'localhost:4200' it made this Error :Access to XMLHttpRequest at 'localhost:8080/user' from origin ..
I tried to solve this problem by adding @CrossOrigin(origins = "*") in the controller and I add a proxy.conf.json in the angular project like I found here : 'https://angular.io/guide/build' But the problem persist .
this is the angular service :
@Injectable({
providedIn: 'root'
})
export class RestService {
api = 'localhost:8080/user'
constructor(private http: HttpClient) { }
getUsers(): Observable<String> {
return this.http.get<String>(this.api);
}
}
this is my proxy.conf.json :
{
"/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
this is the conf in angular.json :
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "crud:build",
"proxyConfig": "src/proxy.conf.json"
}
and this is the spring boot controller :
@RestController
@CrossOrigin(origins = "*")
public class userController {
@GetMapping("/user")
public String getuser(){
return "the user name is bilel" ;
}
}
Solution
You would not want to tell your Angular service about the target server and its port, it's against the use of the proxy conf.
Call something like a generic api/ root endpoint and map it :
export class RestService {
api = '/api/user'
constructor(private http: HttpClient) { }
getUsers(): Observable<String> {
return this.http.get<String>(this.api);
}
}
And the proxy like that :
{
"/api": {
"target": "http://localhost:8080",
"secure": false
}
}
Answered By - Alain Boudard
Answer Checked By - Willingham (JavaFixing Volunteer)