Angular Universal get host name and origin url to call api

Discussão em 'Angular' iniciado por tyler, Fevereiro 26, 2025.

  1. tyler

    tyler Guest

    I have added Angular Universal in my project and everything was working fine. But now we need mapping for subdomain in our application. For that I need to access the host name and current url to pass this parameters in api. But I am not able to get it on server side.

    I have already tried below urls

    Get hostname and pathname information within Angular Universal

    How do I get the hostname Angular Universal v9.x

    Angular Universal get domain name: Property 'req' does not exist on type 'object'

    Below is my code in server.ts server.ts

    // All regular routes use the Universal engine
    server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl },
    { provide: 'host', useValue: req.get('host') }] });
    });


    Component.ts

    constructor(
    private businessService: BuisnessService,
    @Inject(PLATFORM_ID) private platformId: any,
    @Optional() @Inject('host') private host: any,
    @Optional() @Inject(Request) private request: any,
    private injector: Injector
    ){
    console.log(`body`, host); //getting null
    }

    ngOnInit(): void {
    if (isPlatformServer(this.platformId)) {
    console.log(this.injector.get('host')) //not working
    console.log(this.request,this.host) //not working
    } else {

    console.log('document: ', document.location.hostname);

    }
    this.getDomainInfo(hostname,currentUrl) // how do I get current url and hostname on server side.
    }

    Continue reading...

Compartilhe esta Página