Angular 18中检测公开PDF文件是否存在的实现问题及相关咨询
Hey there! Let's break down what's happening with your Angular 18 PDF existence check and the solution you landed on, plus some context to help clarify the root cause.
First off, your initial Angular code is logically sound on paper: you’re using HttpClient.get() to fetch the PDF as a blob, mapping successful responses to true and catching errors to return false. Here’s your original implementation for reference:
existFile(path: string): Observable<boolean> { return this.httpClient.get(path, { responseType: 'blob' }).pipe( map(() => { console.log('exists', path); return true; }), catchError((e) => { console.log('does not exist', e); return of(false); }) ); }
Why you kept hitting the error block
The issue wasn’t that the PDF didn’t exist (your example URL works perfectly) — it was a CORS (Cross-Origin Resource Sharing) restriction enforced by browsers. Browsers block cross-domain requests unless the target server explicitly allows them via the Access-Control-Allow-Origin header. Since the server hosting that PDF isn’t sending this header, your browser rejected the request, which is why you saw the "Reason: CORS header 'Access-Control-Allow-Origin' missing" message in the network tab.
Your workaround: Using a Java backend
Great call moving the existence check to your Java backend! Unlike browsers, server-side applications don’t have CORS restrictions. Your Java app can safely send a request to the PDF URL, check if it returns a successful status code, and then your Angular app just calls your backend endpoint to get the result. This is hands down the most reliable solution here because you can’t control the CORS settings of the external PDF server.
Alternative browser-side workarounds (with major caveats)
If you ever want to explore client-side options (though they’re far less consistent), here are two things to keep in mind:
- Hidden embedded elements: You could try loading the PDF into a hidden
<object>or<iframe>tag and listen for load/error events. But this only works if the external server allows embedding (some block it withX-Frame-Optionsheaders), and it doesn’t integrate cleanly with your Observable-based Angular code. - HEAD requests instead of GET: Some servers allow lightweight HEAD requests (which only fetch response headers, not the full PDF blob) even if they block GET requests for CORS. But this depends entirely on the external server’s configuration, so it’s not a universal fix.
At the end of the day, your backend-based solution is the most robust approach for this scenario.
内容来源于stack exchange

