Angular 5调用JAX-RS API获取城市列表时出现404错误求助
Hey there, let’s work through that 404 error you’re hitting when trying to pull your city list. This kind of issue usually ties back to proxy configuration gaps, path mismatches between your Angular service and backend API, or missing setup steps. Let’s break down the fixes one by one:
1. Make Sure You’re Using the Proxy-Enabled Startup Command
First things first: double-check you’re launching your Angular app with npm start, not just ng serve. Your package.json correctly defines the start script to load the proxy config, but running ng serve directly skips that proxy setup entirely.
Run this command to confirm:
npm start
2. Fix Proxy Path Matching Logic
Looking at your proxy.config.json, you’ve set the pattern to "/api/*", but your service is making a request to "/api/" (a root path with just a trailing slash). The * wildcard only matches paths that have content after /api/, so your root request might not be getting captured by the proxy.
Update your proxy config to use the ** wildcard (which matches any path under /api/, including the root) and add the changeOrigin flag (critical for handling origin mismatches between Angular’s dev server and your backend):
{ "/api/**": { "target": "http://localhost:8080/QuickDep/Compagne", "secure": false, "changeOrigin": true } }
3. Verify Your JAX-RS Backend Paths
Next, confirm that your JAX-RS backend actually exposes a GET endpoint at http://localhost:8080/QuickDep/Compagne/ (the target URL from your proxy):
- Check your JAX-RS application’s
@ApplicationPathannotation: if it’s set to"Compagne", and your Ville resource class uses@Path("/")with a@GETmethod, the path is correct. - If your city list endpoint lives at a subpath (like
@Path("/villes")), update your Angular service’s base URL to match:private userUrl = '/api/villes'; // Replace '/api/' with this
4. Debug Proxy Forwarding
To confirm the proxy is working as expected:
- Open your browser’s DevTools (Network tab) and look at the
/api/request. Check if the error comes from Angular’s dev server (proxy didn’t forward) or your backend (backend doesn’t have the endpoint). - Test the proxy directly with curl:
If you get the same 404, the proxy isn’t forwarding correctly. If you get a backend-specific error (like CORS or a backend error message), the proxy is working but the backend path is mismatched.curl http://localhost:4200/api/
5. Check Trailing Slash Consistency
Trailing slashes can cause unexpected mismatches. Ensure your proxy target URL doesn’t have a trailing slash unless your backend explicitly expects it. For example, if your backend’s base path is http://localhost:8080/QuickDep/Compagne (no trailing slash), keep the target as is—your service’s /api/ will combine to form the correct full path.
After making these changes, restart your Angular app with npm start and test the endpoint again.
内容的提问来源于stack exchange,提问作者S.Yassine

