Angular调用Companies House API报404:找不到'companies'集合
First off, let's tackle the most likely culprit here: your Basic Authentication setup for the Companies House API. The error Collection 'companies' not found is a bit misleading, but it almost always points to an authentication issue (even though you're not getting a 401) because unauthenticated requests can sometimes be routed incorrectly by their API.
1. Correct Basic Auth Implementation
Companies House requires you to use your API key as the username and leave the password blank for Basic Auth. The key thing you're probably missing is that the credentials need to be Base64-encoded in the format {api_key}: (note the trailing colon, since the password field is empty).
Here's how to fix your httpOptions:
// Replace with your actual Companies House API key const apiKey = 'your_real_api_key_here'; // Encode the API key + empty password (api_key:) to Base64 const encodedAuth = btoa(`${apiKey}:`); private httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', Authorization: `Basic ${encodedAuth}` }) };
Why did Postman work? Postman automatically handles the Base64 encoding when you select "Basic Auth" and input your API key as the username (leaving password empty). Your Angular code was likely using the raw API key instead of the properly encoded string.
2. Clean Up Your Request Logic
Hardcoding the search term in your URL isn't ideal, and using any for the return type makes your code less maintainable. Let's fix both:
Define a Type for the API Response
Based on Companies House's documentation, create an interface to type the response (adjust fields to match what you need):
interface CompanySearchResult { title: string; company_number: string; address_snippet: string; status: string; // Add other fields from the API response as needed } interface CompanySearchResponse { total_results: number; items: CompanySearchResult[]; items_per_page: number; }
Update the Service Method
Make the search term dynamic and use your new type:
private baseSearchUrl = 'https://api.companieshouse.gov.uk/search/companies'; getCompany(searchTerm: string): Observable<CompanySearchResponse> { // Encode the search term to handle spaces/special characters const url = `${this.baseSearchUrl}?q=${encodeURIComponent(searchTerm)}`; return this.http.get<CompanySearchResponse>(url, this.httpOptions); }
3. Verify the Request
After making these changes, check your network tab in the browser to confirm:
- The
Authorizationheader matches the one generated by Postman (you can copy Postman's auth header directly to test if needed) - The request URL is correctly formatted with your search term
Quick Troubleshooting Tip
If you're still hitting issues, try copying the exact request headers from Postman into your Angular httpOptions to rule out any encoding differences. Once that works, you can switch back to generating the encoded auth string programmatically.
内容的提问来源于stack exchange,提问作者Darren Street

