Angular 7 HttpClient调用URL自动添加localhost:4200问题的解决办法
Hey there, let's troubleshoot why your API request is getting prefixed with http://localhost:4200/ instead of using your intended AWS API URL. This is a common gotcha with relative vs absolute URLs in Angular, so let's break down the fix step by step.
The Root Cause
Your appConfigService.apiUrl value is written as https//xxxx-api.eu-west-3.amazonaws.com:80/int/ — notice the missing colon after https! Angular treats any URL that doesn't start with a valid protocol (http:// or https://) as a relative path, so it automatically appends it to your local development server's base URL (http://localhost:4200/). That's exactly why you're seeing the messed-up combined URL.
Step-by-Step Fixes
1. Correct the API URL Format
First and foremost, fix the protocol in your API URL to include the colon:
// Update this in your appConfigService apiUrl: string = "https://xxxx-api.eu-west-3.amazonaws.com:80/int/";
With this corrected, Angular will recognize it as an absolute URL and won't prepend the localhost base path.
2. Verify URL Concatenation
Double-check that the url parameter you're appending doesn't introduce unexpected relative path behavior. For example:
- If
urlismeeting, your final URL will behttps://xxxx-api.eu-west-3.amazonaws.com:80/int/meeting(correct). - If
urlstarts with a slash like/meeting, you'll gethttps://xxxx-api.eu-west-3.amazonaws.com:80/int//meeting(harmless but messy — you can adjust either the apiUrl to omit the trailing slash or the url to remove the leading slash for cleaner formatting).
3. Optional: Validate the Final URL Before Request
To confirm everything's working as expected, you can log the final URL before making the request:
const finalUrl = this.appConfigService.apiUrl + url; console.log('Final API URL:', finalUrl); // Should show the full AWS URL without localhost this.http.get(finalUrl, { headers: this.getHeaders(), params: urlParams });
Extra Check: Proxy Configuration (If Applicable)
If you've set up a proxy config (proxy.conf.json) for local development, make sure it's not inadvertently capturing absolute URLs. But in your case, since you're targeting an external AWS API, you likely don't need proxying here — just ensuring the URL is absolute will resolve the issue.
内容的提问来源于stack exchange,提问作者Stéphane GRILLON

