Angular5使用JSONP调用接口时遇Uncaught SyntaxError错误求助
Hey there! I see exactly where the issue is—you’re mixing up what JSONP is designed for and the type of resource you’re trying to request. Let’s break this down clearly:
Why You’re Getting the Unexpected token % Error
JSONP works by loading a JavaScript file that wraps JSON data in a specified callback function (like JSONP_CALLBACK({"key": "value"})). But right now, you’re requesting a .pdf file, which returns binary PDF content (most PDFs start with %PDF-1.x). When the browser tries to parse this PDF content as a JSONP script, it hits the % character immediately and throws that syntax error.
The Correct Approach
You don’t need JSONP to fetch a PDF file—JSONP is only for cross-domain JSON data. Here’s what you should do instead:
1. Fetch the PDF as Binary Data
Use Angular’s HttpClient.get with the correct response type to handle the PDF blob:
this.http.get('http://localhost/angular5/lesson2.pdf', { responseType: 'blob' }) .subscribe(res => { // Option 1: Open the PDF in a new tab for preview const pdfUrl = window.URL.createObjectURL(res); window.open(pdfUrl); // Option 2: Trigger a download for the user const downloadLink = document.createElement('a'); downloadLink.href = pdfUrl; downloadLink.download = 'lesson2.pdf'; downloadLink.click(); // Clean up the object URL to free memory window.URL.revokeObjectURL(pdfUrl); });
2. Double-Check Your Intent
If you actually meant to call an API that returns JSON data (not a PDF), make sure you’re targeting the correct API endpoint (not a .pdf file path). The endpoint should return data wrapped in the JSONP_CALLBACK function you specified, like:
JSONP_CALLBACK({ "data": "your-api-response-content" })
Quick Setup Confirmation
Just to cover all bases—you did correctly add HttpClientJsonpModule to your AppModule’s imports array, right? That part is required for JSONP to work, but it’s not the root cause here since the problem stems from requesting the wrong resource type.
内容的提问来源于stack exchange,提问作者Pranab V V

