Angular 4使用HttpClient调用Zomato API出现403错误求助
Fixing Zomato API 403 Forbidden Error in Your Angular Code
Let's walk through the issues in your current code that are likely causing the 403 error, plus some additional checks to get your request working smoothly:
Key Issues in Your Code
- Incorrect
HttpClient.get()parameter order: Angular'sgetmethod expects the URL first, then the options object (where headers are configured). You added an empty string as the second parameter, which breaks how headers are passed to the request. - Redundant
res.json()call: The AngularHttpClientautomatically parses JSON responses, so you don't need to call this method explicitly—just use theresobject directly. - Unnecessary headers: For a GET request to Zomato's API, the
content-typeheader isn't needed (since there's no request body). Including it might add unnecessary overhead or even confuse the API server. - Potential scope issue with
url: Make sure theurlvariable is accessible within yoursendGetRequestmethod (e.g., define it as a class property if this is part of an Angular service or component).
Corrected Code Example
// Define the URL as a class property for easy access private apiUrl = 'https://developers.zomato.com/api/v2.1/search?count=50&lat=111&lon=111&radius=1500&order=desc'; sendGetRequest() { const headers = new HttpHeaders() .set('cache-control', 'no-cache') .set('user-key', 'mykeygoeshere'); // Keep only the headers the API actually needs this.httpClient.get(this.apiUrl, { headers: headers }) .subscribe(res => { console.log('API Response:', res); // Handle your response data here }, error => { console.error('Request Error:', error); // Add error handling to debug issues like 403s }); }
Additional Troubleshooting Steps
- Verify your
user-key: Double-check that your key is active and valid in the Zomato Developer Dashboard. Sometimes keys take a few minutes to activate after creation, or might be revoked if you've exceeded rate limits. - Test with a tool like Postman: Send the same request (with your key and parameters) through Postman first. If it works there, the issue is definitely in your code; if not, your key or parameters are the problem.
- Check parameter validity: Ensure your
latandlonvalues are valid (111 is outside the standard -90 to 90 range for latitude, which might be causing issues even if your key is correct).
内容的提问来源于stack exchange,提问作者N B
相关产品推荐
相关产品推荐

