I’m working on a project that combines Django as the backend and Angular as the frontend. I’ve set up Django REST framework and it runs on 127.0.0.1:8000
while Angular development server runs on 127.0.0.1:4200
.
When I try to make HTTP requests from Angular, they’re being sent to the Angular server instead of the Django backend. Here’s my current component:
export class DataComponent implements OnInit {
items: any;
dataLoaded: boolean = false;
errorOccurred: boolean = false;
constructor(private httpClient: HttpClient) { }
ngOnInit() {
this.httpClient.get('/api/items').subscribe(response => {
this.items = response;
console.log(response);
}, err => {
this.dataLoaded = true;
this.errorOccurred = true;
console.log(err);
})
}
}
The problem is that when I call /api/items
, it tries to fetch from 127.0.0.1:4200/api/items
instead of my Django server at 127.0.0.1:8000/api/items
.
I know I could create a service with a base URL variable and concatenate it with each request, but is there a cleaner way to automatically redirect all API requests to the backend server without manually adding the full URL every time?
yeah proxy config is defintely the way to go here. just add "start": "ng serve --proxy-config proxy.conf.json"
to your package.json scripts and create the proxy file with /api/*
pointing to your django server. works like a charm and no need to hardcode urls everywhere
hmm interesting setup! have you looked into angular’s proxy configuration? you can create a proxy.conf.json
file to redirect api calls automatically. curious tho - are you planning to deploy these seperately later or keep them together? that might affect which approach works best for you!
Beyond the proxy configuration mentioned above, consider setting up Angular’s HttpInterceptor
for a more robust solution. This approach allows you to intercept all HTTP requests and modify them programmatically. You can create an interceptor that automatically prepends your Django server URL to relative paths starting with /api/
. This method provides better control over request handling and makes it easier to switch between development and production environments. Additionally, you can handle authentication tokens and error responses consistently across your application. The interceptor approach scales better when you have multiple API endpoints or need to implement complex request transformation logic.