I’m having trouble setting up a proxy for my Angular project to communicate with my Express backend. I’ve followed the steps for configuring the proxy, but it’s not working as expected.
My setup:
- Express backend on port 8080
- Angular frontend on port 4200
I created a proxy.conf.json
file in my Angular project:
{
"/api": {
"target": "http://localhost:8080",
"secure": false
}
}
I updated the start
script in package.json
:
"start": "ng serve --proxy-config proxy.conf.json"
When I run npm start
, I see the message Proxy created: /api -> http://localhost:8080
.
In my Angular component, I’m trying to make a request:
constructor(private http: Http) {
this.fetchData();
}
fetchData(): void {
this.http.get("/api/data").subscribe(
response => console.log(response)
);
}
However, I’m getting a 404 error: http://localhost:4200/api/data 404 (Not Found)
.
The backend works fine when I access it directly at http://localhost:8080/data
.
Any ideas why the proxy isn’t working? What am I missing?
hey mate, i had similar issue. check ur backend cors settings. sometimes it messes with proxy. also, try using HttpClient instead of Http (it’s deprecated). and make sure ur using the latest angular cli version. hope this helps!
I encountered a similar issue when setting up my Angular project’s proxy configuration. One crucial detail to check is whether your Express backend is correctly set up to handle routes with the ‘/api’ prefix. If your backend route is just ‘/data’, the proxy won’t work as expected.
Try modifying your Express route to include the ‘/api’ prefix, like this:
app.get(‘/api/data’, (req, res) => {
// Your data handling logic here
});
Additionally, ensure that your Angular HttpClientModule is properly imported in your app.module.ts file. Sometimes, overlooking this step can cause proxy issues.
If these suggestions don’t resolve the problem, consider checking your network tab in the browser’s developer tools to see if there are any CORS-related errors or unexpected redirects happening during the request.
have u tried clearing ur browser cache? sometimes that can mess with proxy stuff. also, maybe double-check ur express app is actually running on port 8080? oh, and r u using any environment variables that might be overriding ur proxy settings? just some thoughts. let us know if u figure it out!