You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular2中如何获取HTTP GET请求的发送域名

How to Get the Request's Origin Domain in Angular

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"
    

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:54:45