Angular CLI backend proxy configuration not working

I’m having trouble setting up a proxy for my Angular project to communicate with my Express backend. I’ve followed the instructions 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:

{
  "/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 Proxy created: /api -> http://localhost:8080.

Here’s my Angular service:

constructor(private httpClient: HttpClient) {
  this.fetchData();
}

fetchData(): void {
  this.httpClient.get("/api/data").subscribe(
    result => console.log(result),
    error => console.error(error)
  );
}

But I get a 404 error: http://localhost:4200/api/data Not Found

The backend works fine when I access it directly at http://localhost:8080/data.

Any ideas why the proxy isn’t working? Did I miss something in the setup?

hey, u tried clearing cache? check if the route in the express matches /api/data, since the backend may use /data instead. curious, what angular version are u working with?

yo, make sure ur express backend is actually running when u test. also, try changing the proxy config to ‘/api/*’ instead of just ‘/api’. sometimes that helps. and double-check ur backend route - it should be ‘/api/data’ not just ‘/data’ to match ur angular service

Have you checked if your Express backend is correctly handling the ‘/api’ prefix? Sometimes the issue lies in how the backend routes are set up. Try modifying your Express routes to include the ‘/api’ prefix, like this:

app.get(‘/api/data’, (req, res) => {
// Your data handling logic here
});

Also, ensure your Express app is using body-parser middleware correctly if you’re sending POST requests. If the problem persists, try adding a ‘changeOrigin’ flag to your proxy config:

{
‘/api’: {
‘target’: ‘http://localhost:8080’,
‘secure’: false,
‘changeOrigin’: true
}
}

This can help in some cases where the host header is causing issues. Let us know if any of these suggestions help resolve the problem.