Angular2中如何获取HTTP GET请求的发送域名
Hey there! Great to see you working through Angular query params—you’re already doing it right with this.route.snapshot.queryParams to grab GET parameters. Now let’s break down how to get the origin domain of the request.
There are two solid approaches, depending on your project’s needs:
1. Quick & Simple: Use window.location
If you’re building a client-only Angular app (no Server-Side Rendering), you can directly access the browser’s window.location object to pull domain details:
- To get the full origin (includes protocol, domain, and port if used):
const requestOrigin = window.location.origin; // Example outputs: "https://yourdomain.com" or "http://localhost:4200" - If you only need the raw hostname (no protocol or port):
const requestHostname = window.location.hostname; // Example outputs: "yourdomain.com" or "localhost"
2. Angular-Recommended: Inject DOCUMENT
For better compatibility with Server-Side Rendering (like Angular Universal) or unit testing, Angular advises avoiding direct window calls. Instead, inject the DOCUMENT token:
First, import the required dependencies in your component or service:
import { Component } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { Inject } from '@angular/core';
Then inject it in your constructor and access location properties:
@Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { constructor(@Inject(DOCUMENT) private document: Document) {} getRequestDomain() { const origin = this.document.location.origin; const hostname = this.document.location.hostname; // Use origin or hostname as needed console.log('Request origin:', origin); } }
A quick clarification: Both methods return the domain of your Angular app’s current page—this is the "sending domain" of the initial page load request. If you’re asking about the domain of an API request you’re making from Angular, you’ll want to reference the base URL you’re using for those HttpClient calls instead.
内容的提问来源于stack exchange,提问作者Midhilaj

