Angular实现Google URL短链接服务遇401认证错误求助
Hey, I see you're hitting a 401 error with the Google URL Shortener API in your Angular service, even though the same API key works fine in AngularJS. Let's break down what's going on and fix it.
The Root Cause
The main issue here is how Angular's HttpClient handles request parameters compared to AngularJS's $http. In AngularJS, passing a plain object to params automatically converts it into URL query parameters. But Angular's HttpClient expects params to be an HttpParams object for proper parsing. Google's URL Shortener API requires your API key to be sent as a URL query parameter (key=XXXXXX), and when you pass a plain object, it might not be getting attached to the URL correctly—hence the "Invalid Credentials" error (the error message mentions the Authorization header, but that's a red herring here; we don't need an Authorization header for API key auth).
Fixed Service Code
Here's the corrected version of your service method. We'll use HttpParams to properly attach the API key, and also extract the actual short URL from the API response (it lives in the id field):
import { HttpClient, HttpParams } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map, catchError } from 'rxjs/operators'; // ... your service class definition urlShortener(longUrl: string): Observable<string> { const requestBody = { longUrl: longUrl }; // Create HttpParams to hold the API key const requestParams = new HttpParams().set('key', 'XXXXXX'); return this.http.post('https://www.googleapis.com/urlshortener/v1/url', requestBody, { params: requestParams }) .pipe( map((response: any) => { console.debug('API Response:', response); // Return the shortened URL from the 'id' field return response.id; }), catchError(this.handleError) ); } // Alternative: You can also directly append the key to the URL if you prefer // return this.http.post('https://www.googleapis.com/urlshortener/v1/url?key=XXXXXX', requestBody) // .pipe(...)
Why This Works When AngularJS Did
AngularJS's $http is more lenient with parameter types and automatically serializes plain objects into query strings. Angular's HttpClient enforces stricter type handling to avoid unexpected behavior, so using HttpParams ensures your API key is correctly encoded and attached to the request URL. The API can then recognize your valid key and return the shortened URL as expected.
内容的提问来源于stack exchange,提问作者Varun Sukheja

