角度通用SSR,第一次调用查找用户的IP是从服务器而不是客户端?



我们制作了 Angular 通用服务器端渲染应用程序,以便出于 SEO 目的在视图源代码中显示 html 标签。我们已在我们的应用程序中实施了本地化,以便根据国家/地区提供数据。我们在应用程序开始时找到 IP,然后使用该 IP 获取该特定国家/地区的数据。

问题是在 SSR 之后,应用程序首先从服务器呈现,ip 调用从服务器发出并找到服务器的 ip。但是我们想要客户端浏览器的ip。他们有什么办法可以解决这个问题吗?

您需要为角度应用提供客户端 IP 地址

app.engine('html', (_, options, callback) =>
ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP),
{
provide: 'clientIPAddress',
useValue: options.req.connection.remoteAddress, //Provides the client IP address to angular
},
],
})(_, options, callback)
)

然后在角度应用中,注入该值

import { Injectable, Inject, Optional } from '@angular/core';

export class YourServiceOrComponent{
constructor(@Optional() @Inject('clientIPAddress') ipAddress: string) 
{
if(ipAddress)
{
//Server side
}
else
{
//client side
}
}   

最新更新