JSONP调用TheMovieDB API本地正常但部署后失效问题求助
Let's break down why your JSONP-based TMDB API call works locally but fails in production, and fix it step by step:
1. Fix URL Escaping Issue (Critical!)
Looking at your API URL, you're using & instead of plain & to separate parameters. This is an HTML entity escape that might get silently corrected by your local dev server, but it will break in production—TMDB will interpret amp;callback as an invalid parameter instead of callback, so it won't return the JSONP-wrapped response your app expects.
Update your getList method to use proper & separators:
getList(input) { const url = 'https://api.themoviedb.org/3/search/movie/?api_key=b6dba21fefcead0c857d43&callback=JSONP_CALLBACK&query=' + input; return this.jsonp.request(url, { method: 'Get' }); }
2. Switch to HttpClient with CORS (More Reliable Than JSONP)
JSONP is a legacy workaround for CORS, and TMDB's API fully supports modern CORS. Using Angular's HttpClient instead will avoid JSONP-specific quirks and make your code cleaner:
Update the Service:
First, make sure HttpClientModule is imported in your AppModule. Then rewrite your service method:
// Inject HttpClient instead of Jsonp constructor(private http: HttpClient) {} getList(input: string) { return this.http.get('https://api.themoviedb.org/3/search/movie', { params: { api_key: 'b6dba21fefcead0c857d43', query: input } }); }
Update the Component Subscription:
You no longer need to access _body—HttpClient parses the JSON response automatically:
this.sharedService.getList(message) .subscribe(data => { this.dataResult = <FilmCard[]>data['results']; });
3. Secure Your API Key (Production Must-Do)
Hardcoding your TMDB API key in the code is a security risk—anyone can extract it from your deployed app. Use Angular's environment files to store it:
- In
src/environments/environment.prod.ts:export const environment = { production: true, tmdbApiKey: 'your-production-api-key' }; - Then reference it in your service:
import { environment } from '../environments/environment'; // ... params: { api_key: environment.tmdbApiKey, query: input }
4. Verify Production Environment Requirements
- HTTPS Only: TMDB's API uses HTTPS, so your deployed app must also serve over HTTPS. Browsers block mixed-content requests (HTTP → HTTPS) in production.
- CORS Configuration: If you're using a reverse proxy or CDN for deployment, ensure it doesn't block outgoing requests to
api.themoviedb.org. TMDB's API already allows cross-origin requests, so no extra server-side CORS setup is needed.
5. Double-Check JSONP Module Setup (If You Stick With JSONP)
If you prefer to keep using JSONP, confirm:
JsonpModuleis imported in yourAppModule(and not accidentally excluded in production builds).- Your production build tool (e.g., Angular CLI) isn't tree-shaking the JSONP module.
内容的提问来源于stack exchange,提问作者Hamza Haddad

